小编Maz*_*zen的帖子

在if条件中调用Java notify()

我刚刚编写了一个简单的java示例来熟悉wait和notify方法的概念.

这个想法是,在调用时notify(),主线程将打印总和.

MyThread类

public class MyThread extends Thread {
    public int times = 0;

    @Override
    public void run() {

        synchronized (this) {
            try {
                for (int i = 0; i < 10; i++) {
                    times += 1;
                    Thread.sleep(500);
                    if (i == 5) {
                        this.notify();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

主类

public class Main {

    public static void main(String[] args) {

        MyThread t = new MyThread();
        synchronized (t) {
            t.start();
            try { …
Run Code Online (Sandbox Code Playgroud)

java multithreading notify wait

4
推荐指数
1
解决办法
98
查看次数

标签 统计

java ×1

multithreading ×1

notify ×1

wait ×1