当我执行以下代码时
public class ThreadTalk {
public static void main(String[] args) {
SimpleThread obj = new SimpleThread();
Thread t = new Thread(obj, "NewThread");
t.start();
synchronized (obj) {
System.out.println("In Synchronized BLOCK");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Out of Synchronized BLOCK");
}
}
}
class SimpleThread implements Runnable {
public void run() {
System.out.println("The thread running now " + Thread.currentThread());
for (int i = 0; i < 10; i++) {
System.out.println("The val of i= " + i);
}
}
}我得到的输出是
In Synchronized BLOCK
The thread running now Thread[NewThread,5,main]
The val of i= 0
The val of i= 1
The val of i= 2
The val of i= 3
The val of i= 4
The val of i= 5
The val of i= 6
The val of i= 7
The val of i= 8
The val of i= 9
Out of Synchronized BLOCK我期望的输出如下所示
In Synchronized BLOCK
Out of Synchronized BLOCK
The thread running now Thread[NewThread,5,main]
The val of i= 0
The val of i= 1
The val of i= 2
The val of i= 3
The val of i= 4
The val of i= 5
The val of i= 6
The val of i= 7
The val of i= 8
The val of i= 9如果我使用主线程的Synchronized块在SimpleThread对象上设置一个锁,那么当主线程进入休眠状态时,我的NewThread是如何运行的。我的意思是,NewThread不应该等到主线程移除了SimpleThread对象上的锁,因为两个线程都在同一个对象上运行。
发布于 2016-01-09 13:08:05
run()和/或start()不需要任何锁。他们只是运行代码。实际上,您需要让SimpleTread获得与主线程相同的锁,以便这两个线程以某种方式进行同步。
与其尝试在Runnable对象上同步,我认为最好的做法是显式地声明一个单独的对象作为锁。
class ThreadTalk{
public static void main(String[] args){
Object lock = new Object();
SimpleThread obj=new SimpleThread( lock );
Thread t=new Thread(obj,"NewThread");
t.start();
synchronized(lock){
System.out.println("In Synchronized BLOCK");
try{
Thread.sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Out of Synchronized BLOCK");
}
}
}
class SimpleThread implements Runnable{
private final Object lock;
public SimpleThread( Object lock ) { this.lock = lock;}
public void run(){
synchronized( lock ) {
System.out.println("The thread running now "+Thread.currentThread());
for(int i=0;i<10;i++){
System.out.println("The val of i= "+i);
}
}
}
}发布于 2016-01-09 13:05:10
您需要在同一对象(即所谓的"monitor")上的两个线程中进行同步,以使它们相互排斥。
要做到这一点,最简单的方法是使run()方法本身成为synchronized
class SimpleThread implements Runnable {
// See the synchronized modifier on the next line
public synchronized void run() {
System.out.println("The thread running now " + Thread.currentThread());
for (int i = 0; i < 10; i++) {
System.out.println("The val of i= " + i);
}
}
}您还需要确保在线程中启动SimpleThread对象之前对其进行同步,因此需要将t.start();语句移动到synchronized (obj) {块中。如果您不这样做,两个线程仍然不能正确地同步,并且不知道哪个线程将首先运行。
发布于 2016-01-09 13:05:52
synchronized块并不做您认为的事情。这意味着同一时间只能有一个线程在其内部(或者更确切地说,在同一对象上的任何同步块中)。在您的例子中,块中只有一个(主线程)。另一个是执行不同的代码。这是意料之中的。
https://stackoverflow.com/questions/34689841
复制相似问题