【发布时间】:2023-04-07 15:37:01
【问题描述】:
我不确定我是否得到了这个 abous ThreadLocals。有时您可以读到一种常见的做法是将 JDBC 连接作为 ThreadLocals 进行,这样每个线程都会获得自己的连接副本。假设下面的套接字是一个 JDBC 连接。然后我做:
public ThreadLocalSocket() throws IOException {
Runnable runnable = new Runnable() {
ThreadLocal<Socket> threadLocal = new ThreadLocal<>();
@Override
public void run() {
try {
threadLocal.set(new Socket("www.google.com", 80));
} catch (IOException e) {e.printStackTrace();}
Thread thread = Thread.currentThread();
for (int j = 0; j < 10 ; j++) {
Socket sock = threadLocal.get();
if (thread.getName().equals("t1")) {
if (!sock.isClosed()) {
try {
sock.close();
} catch (IOException e) {e.printStackTrace();}
}
}
System.out.println("Thread: " + thread.getName()+ ", is closed? " + sock.isClosed() + ", sock hashCode = " + sock.hashCode());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {e.printStackTrace();}
}
}
};
Thread t1 = new Thread(runnable);
t1.setName("t1");
Thread t2 = new Thread(runnable);
t2.setName("t2");
t1.start();
t2.start();
}
为什么我不能在没有 ThreadLocals 的情况下简单地做到这一点?以下代码 sn-p 中的行为与上面的代码示例完全相同:
public ThreadLocalSocket() throws IOException {
Runnable runnable = new Runnable() {
@Override
public void run() {
Socket socket = null;
try {
socket = new Socket("www.google.com", 80);
} catch (IOException e) {e.printStackTrace();}
Thread thread = Thread.currentThread();
for (int j = 0; j < 10 ; j++) {
if (thread.getName().equals("t1")) {
if (!socket.isClosed()) {
try {
socket.close();
} catch (IOException e) {e.printStackTrace();}
}
}
System.out.println("Thread: " + thread.getName()+ ", is closed? " + socket.isClosed() + ", socket hashCode = " + socket.hashCode());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {e.printStackTrace();}
}
}
};
Thread t1 = new Thread(runnable);
t1.setName("t1");
Thread t2 = new Thread(runnable);
t2.setName("t2");
t1.start();
t2.start();
}
【问题讨论】:
标签: java jdbc thread-local