for (int i = 0; i < 3; i++) {
list.add("test" + i);
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
synchronized (list) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
list.add("test3");
}
}
});
thread.start();
synchronized (list) {
System.out.println(list);
}
我现在不理解的是,打印输出不包含“test3”。在线程停止println结束时不应该同步列表吗?
所以他们应该按顺序排列:
Thread.sleep();
list.add("test3");
println(list);
发生了什么事?
答案 0 :(得分:3)
在线程停止println结束时不应该同步列表吗?
只有在第二个线程的run()
方法的执行(特别是其中synchronized (list)
语句的执行)在主线程的synchronized (list)
语句之前启动时才会出现这种情况。执行。
在thread.start();
之前调用synchronized (list) {System.out.println(list);}
并不能保证在执行synchronized (list) {System.out.println(list);}
之前第二个线程将开始运行。
答案 1 :(得分:0)
我现在不理解的是,打印输出并不包含 &#34; TEST3&#34 ;.在线程暂停期间不应该同步列表 println到底?
这意味着您启动的线程将在主线程之前获得锁定。没有办法保证在Java中。事实上,它似乎反过来工作,主线程在第二个线程之前锁定,阻止第二个线程获取锁定。
您可以尝试使用wait / notify机制来确保主线程正在等待另一个线程终止: import java.util.ArrayList;
for (int i = 0; i < 3; i++) {
list.add("test" + i);
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
synchronized (list) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
list.add("test3");
// Notify the main thread
list.notify();
}
}
});
thread.start();
synchronized (list) {
try {
// wait for the other thread for a specified time to terminate
// this will temporary release the lock for the second thread.
list.wait(5000);
} catch (InterruptedException e) {
// see above..
e.printStackTrace();
}
System.out.println(list);
}