为什么线程不停在第3个?

时间:2016-08-25 13:22:28

标签: java multithreading thread-safety

我正在尝试对线程进行一些练习,我刚开始学习线程和其他东西。

import java.util.logging.Level;
import java.util.logging.Logger;

public class ThreadDemo extends Thread {

    @Override
    public void run() {
        int count = 0;
        for (int i = 0; i <= 5; i++) {
            count++;
            System.out.println("counting" + count);
        }
        if (count == 3) {
            try {
                Thread t = new Thread();
                t.wait(5000);
                System.out.println("thread waiting");
            } catch (InterruptedException ex) {
                Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String[] args) {
        ThreadDemo obj = new ThreadDemo();
        obj.start();
    }
}

给定

的输出
counting1
counting2
counting3
counting4
counting5
counting6

1 个答案:

答案 0 :(得分:-2)

完成测试if (count == 3)后,count的值为6

您的代码只测试一次。

您需要移动其中的for循环之外的代码。

在致电t之前,您还需要锁定wait。这是通过同步块完成的。

@Override
public void run() {
    int count = 0;
    for (int i = 0; i <= 5; i++) {
        count++;
        System.out.println("counting" + count);

        // Moved block
        if (count == 3) {
            try {
                Thread t = new Thread();
                synchronized (t) {  
                    t.wait(5000);
                }
                System.out.println("thread waiting");
            } catch (InterruptedException ex) {
                Logger.getLogger(ThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        // End of moved block
    }
}

输出

counting1
counting2
counting3
thread waiting     // Note: this will be printed after 5 seconds
counting4
counting5
counting6

使用Thread.sleep可以获得类似的结果,但不相同,替换此代码

Thread t = new Thread();
synchronized (t) {  
   t.wait(5000);
}

以下内容:

Thread.sleep(5000);

Thread.sleep和Object.wait之间的区别在于可以唤醒等待获取锁并调用notify(或notifyAll)的线程。

相反,不可能唤醒与Thread.sleep一起睡觉的线程。