繁体   English   中英

在以下Java代码中无法理解线程同步的行为

[英]Unable to understand the behaviour of thread synchronization in following java code

当我执行以下代码时

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

如果我使用主线程的同步块将Lock放在SimpleThread对象上,那么当主线程进入睡眠状态时,NewThread会如何运行,我的意思是NewThread不应该等到Main线程移除SimpleThread上的锁之后对象,因为两个线程都在同一个对象上运行。

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);
         }
       }
    }
}

您需要在同一对象(所谓的“监视器”)的两个线程中进行同步,以使它们互斥。

最简单的方法是使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对象上进行同步, 然后再在Thread中启动它,因此需要移动t.start(); synchronized (obj) {块内的语句。 如果您不这样做,则两个线程仍会不正确地同步,并且无法确定哪个线程将首先运行。

synchronized块不符合您的想法。 这意味着同一时间只能在其中一个线程内(或在同一对象的任何同步块内)。 在您的情况下,块内只有一个(主)线程。 另一个正在执行不同的代码。 这是预期的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM