作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用 java.sql.Connection 和字符串参数创建了一个线程。但从线程内部,我观察到 String 值可用,但 Connection 对象不可用。有什么线索吗?
(编辑问题细节):
嗯,看来连接对象是可用的,但在线程内关闭了。代码如下:
package com.catgen.helper;
import java.sql.Connection;
public class ImageCheckHelper extends Thread{
public Connection conn = null;
public String str = null;
public ImageCheckHelper(Connection conn, String str){
this.conn = conn;
this.str = str;
try{
System.out.println("From inside the constructor");
System.out.println((this.conn!=null)?"Connection is not null":"Connection is null");
System.out.println((this.str!=null)?"String is not null":"String is null");
System.out.println((this.conn.isClosed())?"Connection is closed.":"Connection is not closed");
System.out.println("\n\n");
}catch(Exception e){
e.printStackTrace();
}
}
public void run(){
try{
System.out.println("From inside the thread");
System.out.println((conn!=null)?"Connection is not null":"Connection is null");
System.out.println((str!=null)?"String is not null":"String is null");
System.out.println((conn.isClosed())?"Connection is closed.":"Connection is not closed");
}catch(Exception e){
e.printStackTrace();
}
}
public void initiateImageCheck(){
this.start();
return;
}
}
这是输出:
From inside the constructor
Connection is not null
String is not null
Connection is not closed
From inside the thread
Connection is not null
String is not null
Connection is closed.
最佳答案
在将连接提供给构造函数的时间和在 run() 方法中使用它的时间之间是否有另一个线程关闭连接?我的猜测是,在调用 initiateImageCheck() 返回之后但在 run() 方法进行 isClosed() 检查之前,连接已关闭。
如果没有,您是否可以访问 JDBC 驱动程序的源代码?我想知道它是否在保护自己免受多线程使用的影响。
不保证连接是线程安全的,因此您应该从要使用它的线程内获取连接。
您还可以从两个不同的线程对 conn 进行不同步的访问。公共(public)成员变量也不是一个好主意 - 特别是在需要线程安全的类中。
关于java.sql.Connection 在线程内不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3108783/
我是一名优秀的程序员,十分优秀!