您的位置:首页 > 编程语言 > Java开发

经典的线程协作例子

2014-09-26 21:44 211 查看
两个过程:一个是将蜡图到车上,一个是抛光它。抛光任务在图蜡任务完成之前,是不能执行工作的,而图蜡任务在涂另一层蜡之前,必须等抛光任务完成。

这里使用wait()和notifyAll()挂起和重新启动这些任务。

 

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

//打蜡工人

class Paintor implements Runnable{

 String name;

 Car c1;

 Paintor(String n,Car c){

  c1 = c;

  name = n;

 }

 @Override

 public void run() {

  try {

   c1.paint(name);

  } catch (InterruptedException e) {

   e.printStackTrace();

  }

 }

}

//抛光工人

class Bufffer implements Runnable{

 String name;

 Car c1;

 Bufffer(String n,Car c){

  c1 = c;

  name = n;

 }

 @Override

 public void run() {

  try {

   c1.buff(name);

  } catch (InterruptedException e) {

   e.printStackTrace();

  }

 }

}

 

public class Car {

 private boolean isPainted = false;

 //打蜡

 public synchronized void paint(String worker) throws InterruptedException{

  while(isPainted){

   System.out.println(worker +" is waiting to paint");

   wait();//还没抛光,去休息,把工作位置让出

  }

  System.out.println(worker +" is painting");

  isPainted = true;

  notifyAll();

 }

 //抛光

 public synchronized void buff(String worker) throws InterruptedException{

  while(!isPainted){

   System.out.println(worker +" is waiting to buff");

   wait();//还没打蜡,去休息,把工作位置让出

  }

  System.out.println(worker +" is buffing");

  isPainted = false;

  notifyAll();//所有正在休息的工人出来排队准备干活

 }

 public static void main(String[] args) {

  final Car car1 = new Car();

  ExecutorService es = Executors.newCachedThreadPool();

  for(int i=1;i<=10;i++){//创建10个打蜡工人,10个抛光工人

   es.submit(new Paintor("Painter"+i,car1));

   es.submit(new Bufffer("Bufffer"+i,car1));

  }

  es.shutdown();

 }

}

==================================

某次运行结果:

Painter1 is painting

Painter2 is waiting to paint

Bufffer1 is buffing

Painter2 is painting

Painter3 is waiting to paint

Painter4 is waiting to paint

Painter5 is waiting to paint

Bufffer5 is buffing

Painter5 is painting

Painter4 is waiting to paint

Painter3 is waiting to paint

Bufffer2 is buffing

Painter3 is painting

Painter4 is waiting to paint

Bufffer9 is buffing

Painter7 is painting

Painter4 is waiting to paint

Painter10 is waiting to paint

Painter6 is waiting to paint

Bufffer6 is buffing

Painter6 is painting

Painter10 is waiting to paint

Painter4 is waiting to paint

Painter8 is waiting to paint

Painter9 is waiting to paint

Bufffer3 is buffing

Painter9 is painting

Painter8 is waiting to paint

Painter4 is waiting to paint

Bufffer4 is buffing

Bufffer7 is waiting to buff

Bufffer8 is waiting to buff

Bufffer10 is waiting to buff

Painter10 is painting

Bufffer10 is buffing

Bufffer8 is waiting to buff

Bufffer7 is waiting to buff

Painter4 is painting

Painter8 is waiting to paint

Bufffer7 is buffing

Bufffer8 is waiting to buff

Painter8 is painting

Bufffer8 is buffing

(我的个人博客:http://www.junhong.me/)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程 java