public class Test {
private final Operate operate = new Operate();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 50; i++) {
operate.doSubMethod(i);
}
}
}).start();
for (int i = 1; i <= 50; i++) {
operate.doSupMethod(i);
}
}
}
class Operate{
private boolean isSub = true;
public synchronized void doSubMethod(int i){
while(!isSub){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 12; j++) {
System.out.println("Sub--> " + Thread.currentThread().getName() + "\tloop:" + i + "\t第" + j + "次");
}
isSub = false;
notify();
}
public synchronized void doSupMethod(int i){
while(isSub){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 88; j++) {
System.out.println("Sup--> " + Thread.currentThread().getName() + "\tloop:" + i + "\t第" + j + "次");
}
isSub = true;
notify();
}
}
java 通过使用wait和notify进行线程之间通信(代码)
最新推荐文章于 2024-07-24 00:45:49 发布