文章出處 https://www.jianshu.com/p/6bc888b82008
文章對應視頻出處:https://developer.aliyun.com/course/1012?spm=5176.10731542.0.0.6ef2d290hxQ4g0
設計4個線程對象,2個線程執行減操作,2個線程執行加操作。
public class ThreadDemo {
public static void main(String[] args) throws Exception {
Resource res = new Resource();
SubThread st = new SubThread(res);
AddThread at = new AddThread(res);
new Thread(at, "A ").start();
new Thread(at, "B ").start();
new Thread(st, "X ").start();
new Thread(st, "Y ").start();
}
}
class AddThread implements Runnable {
private Resource resource;
public AddThread(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
this.resource.add();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class SubThread implements Runnable {
private Resource resource;
public SubThread(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
this.resource.sub();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Resource {//定義一個操作的資源
private int num = 0;//這個是要進行加減操作的數據
private boolean flag = true;//加減的切換
//flag = true:表示可以進行加法操作,但是無法進行減法操作
//flag = false:表示可以進行減法操作,但是無法進行加法操作
public synchronized void add() throws InterruptedException {//執行加法操作
while (flag == false) {//現在需要執行的是減法操作,加法操作要等待
System.out.println("【加法操作 -" + Thread.currentThread().getName() + "】進行等待");
super.wait();
System.out.println("【加法操作 -" + Thread.currentThread().getName() + "】被釋放");
}
Thread.sleep(100);
this.num++;
System.out.println("【加法操作 -" + Thread.currentThread().getName() + "】num = " + this.num);
this.flag = false;//加法操作執行完畢,需要執行減法操作
super.notifyAll();//喚醒全部等待線程
}
public synchronized void sub() throws InterruptedException {//執行減法操作
while (flag == true) { //減法操作需要等待,注意:一定要用while 詳見:文章多線程六關於while詳解
System.out.println("【減法操作 -" + Thread.currentThread().getName() + "】進行等待");
super.wait();
}
Thread.sleep(200);
this.num--;
System.out.println("【減法操作 -" + Thread.currentThread().getName() + "】num = " + this.num);
this.flag = true;
super.notifyAll();
}
}
這是一個經典的多線程開發操作,這個程序中一定要考慮的核心本質在於:加一個、減一個,整體的計算結果應該在0、1(或-1) 中循環出現纔是合理的。