//多生產多消費 class resource //將共有資源封裝 { private String name; private int count=1; private boolean flag=false; public synchronized void set(String name)//同步set方法 { if (flag)//如果為假,生產烤鴨,如果為真,等待 { try{this.wait();}catch(InterruptedException e){} } this.name=name+count; count++; System.out.println(Thread.currentThread().getName()+".生產者..."+this.name); flag=true; notifyAll();//防止死鎖問題,喚醒線程池中的全部線程 } public synchronized void out()//同步out方法 { if (!flag)//如果為真,消費烤鴨,如果為假,等待 { try{this.wait();}catch(InterruptedException e){} } System.out.println(Thread.currentThread().getName()+".....消費者"+this.name); flag=false; notifyAll();//防止死鎖問題,喚醒線程池中全部線程 } } class producer implements Runnable { private resource r;//不同的方法訪問一個資源 producer(resource r) { this.r=r; } public void run() { while (true) { r.set("烤鴨"); } } } class consumer implements Runnable { private resource r; consumer(resource r) { this.r=r; } public void run() { while (true) { r.out(); } } } class test { public static void main(String[] args) { resource r=new resource();//為不同的方法設置同一個資源 producer p1= new producer(r); consumer c1=new consumer(r); //創造線程 Thread t1=new Thread(p1); Thread t2=new Thread(p1); Thread t3=new Thread(c1); Thread t4=new Thread(c1); //開啟線程 t1.start(); t2.start(); t3.start(); t4.start(); } }
打印結果為
學習了Lock之后可以顯示地把獲取鎖和釋放鎖表示出來
import java.util.concurrent.locks.*; class resource //將共有資源封裝 { private String name; private int count=1; private boolean flag=false; Lock lock=new ReentrantLock(); Condition con=lock.newCondition(); Condition pro=lock.newCondition(); public void set(String name)//同步set方法 { lock.lock(); try { while (flag)//如果為假,生產烤鴨,如果為真,等待 { try{pro.await();}catch(InterruptedException e){} } this.name=name+count; count++; System.out.println(Thread.currentThread().getName()+".生產者..."+this.name); flag=true; con.signal();//防止死鎖問題,喚醒線程池中的全部線程 } finally { lock.unlock(); } } public void out()//同步out方法 { lock.lock(); try { while(!flag)//如果為真,消費烤鴨,如果為假,等待 { try{con.await();}catch(InterruptedException e){} } System.out.println(Thread.currentThread().getName()+".....消費者"+this.name); flag=false; pro.signal();//防止死鎖問題,喚醒線程池中全部線程 } finally { lock.unlock(); } } } class producer implements Runnable { private resource r;//不同的方法訪問一個資源 producer(resource r) { this.r=r; } public void run() { while (true) { r.set("烤鴨"); } } } class consumer implements Runnable { private resource r; consumer(resource r) { this.r=r; } public void run() { while (true) { r.out(); } } } class test { public static void main(String[] args) { resource r=new resource();//為不同的方法設置同一個資源 producer p1= new producer(r); consumer c1=new consumer(r); //創造線程 Thread t1=new Thread(p1); Thread t2=new Thread(p1); Thread t3=new Thread(c1); Thread t4=new Thread(c1); //開啟線程 t1.start(); t2.start(); t3.start(); t4.start(); } }