Java多執行緒開發——一個簡單的數字加減小例子
阿新 • • 發佈:2018-12-03
範例:
兩個執行緒實現加法,兩個執行緒實現減法
class Resource { private int num = 0; private boolean flag = true; //flag = true 表示可以進行加法操作,不能進行減法操作 //flag = false 表示可以進行減法操作,不能進行加法操作 public synchronized void add() throws InterruptedException { //執行加法操作 if (this.flag == false) { //此處應使用while super.wait(); } Thread.sleep(100); this.num++; System.out.println(Thread.currentThread().getName() + " 加法操作 num = " + num); this.flag = false; super.notifyAll(); } public synchronized void sub() throws InterruptedException { //執行減法操作 if (this.flag == true) { ////此處應使用while super.wait(); } Thread.sleep(200); this.num--; System.out.println(Thread.currentThread().getName() + " 減法操作 num = " + num); this.flag = true; super.notifyAll(); } } class AddThread implements Runnable { private Resource resource; public AddThread(Resource resource) { this.resource = resource; } @Override public void run() { for (int i = 0; i < 50; 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 < 50; i++) { try { this.resource.sub(); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class ThreadDemo1 { public static void main(String[] args) { Resource resource = new Resource(); AddThread addThread = new AddThread(resource); SubThread subThread = new SubThread(resource); new Thread(addThread, "加法執行緒 - A").start(); new Thread(addThread, "加法執行緒 - B").start(); new Thread(subThread, "減法執行緒 - X").start(); new Thread(subThread, "減法執行緒 - Y").start(); } }
此程式碼中有一個問題,數字num會出現一直減一直加的問題,是因為在進行執行緒同步時,Object中的wait()方法執行時會釋放鎖,無法實現同步
As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:
synchronized (obj) { while (<condition does not hold>) obj.wait(timeout, nanos); ... // Perform action appropriate to condition }
上面是官方文件的說明