java并发学习笔记(一):wait() notifyAll() 生产者 消费者

来源:互联网 发布:可意下载 mac 破解版 编辑:程序博客网 时间:2024/05/22 17:15

知道的太少,操作系统还是要补

一、wait()与notifyAll()

参考《thinking in Java》
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;class Car{private boolean waxOn = false;public synchronized void waxed(){waxOn = true;System.out.println("function waxed");notifyAll();}public synchronized void buffed(){waxOn = false;System.out.println("function buffed");notifyAll();}public synchronized void waitForWaxing() throws InterruptedException{System.out.println("function waitforwaxing");while(waxOn == false){System.out.println("waitforwaxing");wait();}}public synchronized void waitForBuffing() throws InterruptedException{System.out.println("function waitforbuffing");while(waxOn == true){System.out.println("waitforbuffing");wait();}}}class WaxOn implements Runnable{private Car car;public WaxOn(Car c){car = c;}@Overridepublic void run() {// TODO Auto-generated method stubtry{while(!Thread.interrupted()){System.out.println("Wax On");TimeUnit.MILLISECONDS.sleep(500);//TimeUnit.SECONDS.sleep(5);car.waxed();car.waitForBuffing();}}catch(InterruptedException e){System.out.println("Exit via interrupt");}System.out.println("Ending Wax On task");}}class WaxOff implements Runnable{private Car car;public WaxOff(Car c){car = c;}@Overridepublic void run() {// TODO Auto-generated method stubtry{while(!Thread.interrupted()){car.waitForWaxing();System.out.println("Wax Off");TimeUnit.MILLISECONDS.sleep(500);car.buffed();}}catch(InterruptedException e){System.out.println("Exit via interrupt");}System.out.println("Ending Wax Off task");}}public class WaxOMatic {public static void main(String[] args) throws Exception{// TODO Auto-generated method stubCar car = new Car();ExecutorService exec = Executors.newCachedThreadPool();exec.execute(new WaxOn(car));exec.execute(new WaxOff(car));//exec.execute(new WaxOff(car));//exec.execute(new WaxOn(car));TimeUnit.SECONDS.sleep(2);exec.shutdownNow();}}

运行结果
Wax Onfunction waitforwaxingwaitforwaxingfunction waxedfunction waitforbuffingwaitforbuffingWax Offfunction buffedfunction waitforwaxingwaitforwaxingWax Onfunction waxedfunction waitforbuffingwaitforbuffingWax OffExit via interruptExit via interruptEnding Wax On taskEnding Wax Off task

将waxed()函数中的notify和main()函数里exec.shutdownNow()注释掉,运行结果
Wax Onfunction waitforwaxingwaitforwaxingfunction waxedfunction waitforbuffingwaitforbuffing
没有notifyAll唤醒wait中的线程后线程一直被挂起

二、生产者&消费者
参考《thinking in Java》
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;class Meal{private final int orderNum;public Meal(int orderNum){this.orderNum = orderNum;}public String toString(){return "Meal "+orderNum;}}class WaitPerson implements Runnable{private Restaurant restaurant;public WaitPerson(Restaurant r){restaurant = r;}@Overridepublic void run() {// TODO Auto-generated method stubtry{while(!Thread.interrupted()){synchronized(this){while(restaurant.meal == null){wait();//for the chef to produce a meal}}System.out.println("waitperson got "+restaurant.meal);synchronized(restaurant.chef){restaurant.meal = null;//restaurant.chef.notifyAll();}}}catch(InterruptedException e){System.out.println("WaitPerson Intererupt");}}}class Chef implements Runnable{private Restaurant restaurant;private int count = 0;public Chef(Restaurant r){restaurant = r;}public void run(){try{while(!Thread.interrupted()){synchronized(this){while(restaurant.meal != null){wait();//for the meal to be taken}}if(++count == 10){System.out.println("Out of food");restaurant.exec.shutdownNow();}System.out.println("Order up!");synchronized(restaurant.waitperson){restaurant.meal = new Meal(count);//restaurant.waitperson.notifyAll();}TimeUnit.MILLISECONDS.sleep(100);}}catch(InterruptedException e){System.out.println("Chef interrupted");}}}public class Restaurant {Meal meal;ExecutorService exec = Executors.newCachedThreadPool();WaitPerson waitperson = new WaitPerson(this);Chef chef = new Chef(this);public Restaurant(){exec.execute(chef);exec.execute(waitperson);}public static void main(String[] args) {// TODO Auto-generated method stubnew Restaurant();}}
总思路还是通过对某一个对象的检测控制顺序,而那个对象在任务之外的类中生成

写了一个程序,print_char线程打印“A B”,print_dig线程打印“1 2”,两个线程配合打印出A B 1 2 A B 1 2...
注释的部分是错误的写法,一定要保证两个线程都是对同一对象的操作
如果想让两个线程对不同对象notifyAll和wait然后使两个线程可协作配合该怎么做?
package ab12;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;class Print_dig implements Runnable{Print print;Print_dig(Print p){print = p;}@Overridepublic void run() {// TODO Auto-generated method stubsynchronized(this){try{while(!Thread.interrupted()){while(!print.now_print_dig){//print char now, so waitwait();}System.out.println("1 2");synchronized(print.print_char){print.now_print_dig = false;print.print_char.notifyAll();}}}catch(InterruptedException e){System.out.println("Thread exec shutdown");}}}}class Print_char implements Runnable{Print print;int count = 1;Print_char(Print p){print = p;}@Overridepublic void run() {// TODO Auto-generated method stubtry{while(!Thread.interrupted()){synchronized(this){while(print.now_print_dig){wait();}}if(count == 10){print.exec.shutdownNow();;}++count;System.out.println("A B");synchronized(print.print_dig){print.now_print_dig = true;print.print_dig.notifyAll();}}}catch(InterruptedException e){e.printStackTrace();}}}class Print{boolean now_print_dig;Print(){now_print_dig = false;}Print_dig print_dig = new Print_dig(this);Print_char print_char = new Print_char(this);ExecutorService exec = Executors.newCachedThreadPool();void print() throws InterruptedException{Print print = new Print();/* * wrong!!!Print_dig print_dig = new Print_dig(this);Print_char print_char = new Print_char(this);exec.execute(print_dig);exec.execute(print_char);*///exec.execute(new Print_dig(this));//exec.execute(new Print_char(this));exec.execute(print_dig);exec.execute(print_char);}}public class Print_AB12 {public static void main(String[] args) throws InterruptedException {// TODO Auto-generated method stubPrint Print = new Print();Print.print();}}
运行结果
A B1 2A B1 2A B1 2A B1 2A B1 2A B1 2A B1 2A B1 2A B1 2A BThread exec shutdown




0 0
原创粉丝点击