我刚刚编写了一个简单的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)