简体   繁体   中英

Thread not printing everything after notifyAll in java

class Lock implements Runnable{
  int i=0;
  public synchronized void run(){
    for(i=0;i<10;i++){
        if(Thread.currentThread().getName().equals("t1") && i == 5)
         {try { this.wait();} catch(InterruptedException ie){}}
        System.out.print(Thread.currentThread().getName()+" ");
        if(Thread.currentThread().getName().equals("t3") && i == 9)
         this.notifyAll();
  }
 }
}
public class ThreadLock {
 public static void main(String[] args){   
  Lock l = new Lock();
  Thread t1 = new Thread(l);
  Thread t2 = new Thread(l);
  Thread t3 = new Thread(l);
  t1.setName("t1");
  t2.setName("t2");
  t3.setName("t3");
  t1.start();
  t2.start();
  t3.start();
 }
}

Output is: t1 t1 t1 t1 t1 t3 t3 t3 t3 t3 t3 t3 t3 t3 t3 t1 t2 t2 t2 t2 t2 t2 t2 t2 t2 t2

t1 is not printing all 10 times after calling notifyAll method. I ran it many times but every time t1 is printed only 6 times. Why t1 is not printing all 10 times? please reply soon

i is an instance variable. It's shared by all the threads. It should be a local variable.

When the first thread is awakened, it reacquires the lock, prints its name, increments i, and reevaluates if i < 10 . But since the other threads have set i to 10 already, the loop stops.

问题是您在线程之间共享相同的索引i ,因此当线程t3存在且t1唤醒时,索引i将为10 ,线程t1中的for循环将退出。

尝试在启动每个线程之后在每个线程上调用.join(),以确保每个线程在程序退出之前完成吗?

While the correct answer is already given by JB Nizet, you might wonder, why this only affects t1 : Every thread is reseting i , when the run method (which is synchronized) is called.

But the moment you RETURN the execution of t1 - it's not going to reset i , since the thread has already started the for -loop.

   i | output
   0 | t1 (FIRST iteration of t1 -> Setting i=0)
   1 | t1
   2 | t1
   3 | t1
   4 | t1
   5 | t1
   0 | t3 (FIRST iteration of t3 -> Setting i = 0)
   1 | t3
   2 | t3
   3 | t3
   4 | t3
   5 | t3
   6 | t3
   7 | t3
   8 | t3
   9 | t3
   0 | t2 (FIRST iteration of t2 -> Setting i = 0)
   1 | t2
   2 | t2
   3 | t2
   4 | t2
   5 | t2
   6 | t2
   7 | t2
   8 | t2
   9 | t2
   9 | t1 (t1 restored, but i=9 now. One more output, program done)

Note: That's at least what is happening for your described output. I think it might also be possible, that t2 is executed before t3, leading to a different output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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