为什么 “wait” 方法在 Thread 对象上不起作用?

huangapple go评论113阅读模式
英文:

Why wait method doesn't work on Thread object?

问题

Thread t2 = new Thread();
Thread t3 = new Thread();

t1.start();
t2.start();
synchronized (t2) {
	t2.wait(20000);
}
t3.start();

上述程序运行时,t2并不会等待20秒。我观察到当线程对象启动时,它不会等待。为什么会发生这种情况?

英文:
Thread t2 = new Thread();
Thread t3 = new Thread();

t1.start();
t2.start();
synchronized (t2) {
	t2.wait(20000);
}
t3.start();

The above program runs without t2 waiting for 20sec. I observed that when thread object is started then it wont wait. Why is this happening?

答案1

得分: 1

为什么会发生这种情况?

首先,让我们明确一点。这个函数调用,t2.wait(20000)t2 线程没有任何影响。实际上,它实际上什么事情都没做。它所做的就是在以下两种情况发生之前不会返回:

  • 其他某个线程调用了 t2.notify(),或者
  • 经过了20秒的时间。

如果调用在不到20秒内返回,那可能是因为 t2 线程在即将终止之前调用了 t2.notify()。在大多数 Java 标准库的实现中,join() 方法是通过在线程对象上使用 wait()notify() 调用来实现的。

(注意:大多数作者会建议您永远不要在 Thread 实例上调用 wait()notify(),正是因为当代码和库代码同时对同一实例调用相同方法时可能会产生干扰。)

上述程序在没有使t2等待20秒的情况下运行。

正如其他人在这里已经指出的,您没有为 t2 线程提供任何 run() 方法,因此不清楚为什么您期望 t2 线程会“等待”,或者根本不做任何其他操作。线程唯一做的事情就是在 run() 方法中执行您提供的代码。

默认的 Thread.run() 方法会调用您在构造线程时提供的 委托 对象的 run() 方法,但是您的代码没有提供委托。在这种情况下,默认的 run() 方法根本不执行任何操作。

英文:

> Why is this happening?

First, let's be clear. This function call, t2.wait(20000) does not do anything to the t2 thread. In fact, it doesn't really do anything at all. All it does is not return until either one of two things happens;

  • Some other thread calls t2.notify(), or
  • 20 seconds elapse.

If the call took less than 20 seconds to return, then that's probably because the t2 thread itself called t2.notify() just before it died. In most implementations of the Java standard library, the join() method is implemented by using wait() and notify() calls on the thread object.

(Note: most authors will advise you not to ever call wait() or notify() on a Thread instance precisely because of the potential for interference between your code and the library code when both call the same methods on the same instance.)

> The above program runs without t2 waiting for 20sec.

As somebody else already has pointed out here, You have not provided any run() method for your t2 thread, so it's unclear why you would expect the t2 thread to "wait" or, to do anything else at all. The only thing a thread ever does is execute the code that you provide for it in a run() method.

The default Thread.run() method would call the run() method of a delegate object that you supply when you construct the threads, but your code supplies no delegate. In that case, the default run() method does nothing at all.

答案2

得分: 0

使用 sleep 使线程暂停,而不管是否有工作要完成。
wait 不会暂停线程,它只是等待线程完成(而此线程已经完成)。

英文:

Use sleep to pause the thread regardless of having work to finish.
wait doesn't pause the thread, it just waits the thread to finish (and this thread already finished).

答案3

得分: 0

class SleepThread extends Thread  {    
    //线程的run方法
    public void run()    {    
        for(int i=1;i<5;i++)   {    
            try  {  
                //调用线程的sleep方法
                Thread.sleep(20000);  
            }catch(InterruptedException e){
                System.out.println(e);
            }    

            //打印当前线程实例以及循环变量
            System.out.println(Thread.currentThread().getName() + "   : " + i);    
        }    
    }    
}

class Main{
    public static void main(String args[]){  
        //创建两个线程实例
        SleepThread thread_1 = new SleepThread();    
        SleepThread thread_2 = new SleepThread();    
        //依次启动线程
        thread_1.start();    
        thread_2.start();    
    }    
}  

[Java中的Thread.sleep方法][1]
英文:
class SleepThread extends Thread  {    
  //run method for thread
    public void run()    {    
        for(int i=1;i&lt;5;i++)   {    
            try  {  
              //call sleep method of thread
              Thread.sleep(20000);  
            }catch(InterruptedException e){
              System.out.println(e);
            }    

          //print current thread instance with loop variable
          System.out.println(Thread.currentThread().getName() + &quot;   : &quot; + i);    
        }    
    }    
}

class Main{
   public static void main(String args[]){  
     //create two thread instances
        SleepThread thread_1 = new SleepThread();    
        SleepThread thread_2 = new SleepThread();    
    //start threads one by one
        thread_1.start();    
        thread_2.start();    
    }    
}  

Thread sleep method in java

huangapple
  • 本文由 发表于 2020年9月20日 17:42:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63977542.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定