多线程学习(十三)

线程协作

正如以前所见的多线程同时运行多个任务时候,可以通过使用锁(互斥)来同步两个任务的行为。从而使得一个任务不会干涉另一个任务的资源
线程协作,现在的问题不是彼此干涉而是彼此之间的协调。当任务协调的时候,关键是这些任务之间的握手。为了实现握手我们使用了相同的基础特性:互斥。这种情况下,互斥确保了只有一个任务可以响应某个信号。这样可以根除所有可能的竞态条件。在互斥的基础上,我们为任务添加了一种新的途径,可以将自身挂起,直到外部条件发生变化,表示可以让这个任务开动了。这种握手可以通过
Object的方法wait() 和notify() 来安全实现。JAVA SE5 中还提供了具有 await 和 signal 方法的Condition对象

wait 和 notifyAll

首先理解这一点 调用Sleep和yield 的时候锁并没有被释放 当一个任务中的方法遇到对wait的调用的时候,线程执行将别挂起,对象上的锁将被释放,因此该对象的 synchronized可以在 wait的期间被调用

public class Car {
	private boolean waxOn = false;

	public synchronized void waxOn() {
		waxOn = true;
		notifyAll();
	}

	public synchronized void buff() {
		waxOn = false;
		notifyAll();
	}
	public synchronized void waitingForWaxOn() throws InterruptedException{
		if(waxOn==false){ //不能省略
			wait();
		}
	}

	public synchronized void waitingForBuff() throws InterruptedException {
		if(waxOn==true){  //不能省略
			wait();
		}
	}
}
import java.util.concurrent.TimeUnit;

public class WaxOn implements Runnable {
	private Car car;
	
	public WaxOn(Car car) {
		this.car = car;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
			try {
				while(!Thread.interrupted()){
				System.out.println("Wax on");
				TimeUnit.MILLISECONDS.sleep(500);
				car.waxOn();
				car.waitingForBuff();
				}
			} catch (InterruptedException e) {
				System.out.println("waxon interrupt");
			}
			System.out.println("exiting waxon");
	}

}
import java.util.concurrent.TimeUnit;

public class WaxOff implements Runnable {
	private Car car;

	public WaxOff(Car car) {
		this.car = car;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			while (!Thread.interrupted()) {
				car.waitingForWaxOn();
				System.out.println("Wax off");
				TimeUnit.MILLISECONDS.sleep(500);
				car.buff();
			}
		} catch (InterruptedException e) {
			System.out.println("waxoff interrupt!");
		}
		System.out.println("exiting waxoff");
	}

}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class WaxCarTest {
public static void main(String[] args) throws Exception {
	ExecutorService exec=Executors.newCachedThreadPool();
	Car car =new Car();
	exec.execute(new WaxOff(car));
	exec.execute(new WaxOn(car));
	
	TimeUnit.SECONDS.sleep(3);
	
	exec.shutdownNow();// interrupet all threads
}
}


这里可以看到线程协作

错失的信号:
当两个线程notify/wait或

public class Blocker {
	synchronized void wa()  {
		try {
			while (!Thread.interrupted()) {
				wait();
				System.out.println("thread:" + Thread.currentThread().getName());
			}
		} catch (InterruptedException e) {
			System.out.println("task2 interrupt");
		}
	}

	synchronized void no() {
		notify();
	}

	synchronized void noall() {
		notifyAll();
	}
}
public class Task implements Runnable {
	static Blocker blocker =new Blocker();
	@Override
	public void run() {
		blocker.wa();
	}

}
public class Task2 implements Runnable {
	static Blocker blocker = new Blocker();

	@Override
	public void run() {
		blocker.wa();
	}

}
public class NotifyVSNotifyAll {
	public static void main(String[] args) throws Exception {
		ExecutorService exec = Executors.newCachedThreadPool();
		for (int i = 0; i < 5; i++) {
			exec.execute(new Task());
		}
		exec.execute(new Task2());
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			boolean flag = false;

			@Override
			public void run() {
				if (flag) {
					Task.blocker.no();
					System.out.println("Task notify!");
					flag = false;
				} else {
					Task.blocker.noall();
					System.out.println("Task notifyAll");
					flag = true;
				}
			}
		}, 400, 400);

		TimeUnit.MILLISECONDS.sleep(1500);
		timer.cancel();
		TimeUnit.MILLISECONDS.sleep(300);
		System.out.println("timer cancal");
//		Task2.blocker.no();
//		System.out.println("Task2 notify");
//		TimeUnit.MILLISECONDS.sleep(200);
		Task2.blocker.noall();
		System.out.println("Task2 notifyAll");
		TimeUnit.MILLISECONDS.sleep(200);
		exec.shutdownNow();

	}
}


根据输出可以看出notify其实只会唤醒等待这个锁的任务才会被唤醒。

生产者消费者模式
餐厅中只有一个厨师一个服务员 厨师(Producer)生产菜服务员(Consumer)传菜

public class Meal {
	private int id;

	public Meal(int id) {
		super();
		this.id = id;
	}

	@Override
	public String toString() {
		return "Meal [id=" + id + "]";
	}
	
}
public class Chef implements Runnable {
	private int count = 0;
	private Restaurant restaurant;

	public Chef(Restaurant restaurant) {
		super();
		this.restaurant = restaurant;
	}

	@Override
	public void run() {
		try {
			while (!Thread.interrupted()) {
				synchronized (this) {
					while (restaurant.meal != null) {
						wait();
					}
				}
				System.out.println("chef produce meal");
				if (++count > 10) {
					System.out.println("produce to much");
					restaurant.exec.shutdownNow();// stop all thread!
				}
				synchronized(restaurant.waiter){
					restaurant.meal=new Meal(count);
					restaurant.waiter.notify();
				}
			}
		} catch (InterruptedException e) {
			System.out.println("interrupt chef");
		}
	}

}
public class Restaurant {
	Chef chef = new Chef(this);
	Waiter waiter = new Waiter(this);
	Meal meal = new Meal(0);
	ExecutorService exec = Executors.newCachedThreadPool();

	public Restaurant() {
		exec.execute(chef);
		exec.execute(waiter);
	}

	public static void main(String[] args) {
		new Restaurant();
	}
}
public class Waiter implements Runnable {
	private Restaurant restaurant;

	public Waiter(Restaurant restaurant) {
		super();
		this.restaurant = restaurant;
	}

	@Override
	public void run() {
		try {
			while (!Thread.interrupted()) {
				synchronized (this) {
					while (restaurant.meal == null) {
						wait();
					}
				}
				System.out.println("waiter consume " + restaurant.meal);
				synchronized (restaurant.chef) {
					restaurant.meal = null;
					restaurant.chef.notify();
				}
			}
		} catch (InterruptedException e) {
			System.out.println("waiter interrupt");
		}
	}

}

JAVA SE5 提供了Lock和Condition对象
可以在Condition对象上面调用await挂起一个任务。
也可以调用signal来通知这个任务,从而唤醒这个任务。也可以使用signall来唤醒这个Condition上挂起的所有任务(必去notifyAll,signalAll是更安全的方式)
下面用 Lock和Condition重写 Car 那一个例子

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Car {
	private boolean flag = false;
	private Lock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();

	public void maxOn() {
		lock.lock();
		try {
			flag = true;
			condition.signalAll();
		} finally {
			lock.unlock();
		}
	}

	public void maxoff() {
		lock.lock();
		try {
			flag = false;
			condition.signalAll();
		} finally {
			lock.unlock();
		}
	}

	public void waitingForMaxOn() throws InterruptedException {
		lock.lock();
		try {
			if (flag == false) {
				condition.await();
			}
		} finally {
			lock.unlock();
		}
	}

	public void waitingForMaxOff() throws InterruptedException {
		lock.lock();
		try {
			if (flag == true) {
				condition.await();
			}
		} finally {
			lock.unlock();
		}
	}
}

public class WaxOn implements Runnable {
	private Car car;

	public WaxOn(Car car) {
		super();
		this.car = car;
	}

	@Override
	public void run() {
		try {
			while (!Thread.interrupted()) {
				System.out.println("  wax on  ");
				car.maxOn();
				car.waitingForMaxOff();
			}
		} catch (InterruptedException e) {
			System.out.println("waxon interrupt");
		}
	}
}

public class WaxOff implements Runnable {
	private Car car;

	public WaxOff(Car car) {
		super();
		this.car = car;
	}

	@Override
	public void run() {
		try {
			while (!Thread.interrupted()) {
				car.waitingForMaxOn();
				System.out.println("  wax off  ");
				car.maxoff();
			}
		} catch (InterruptedException e) {
			System.out.println("waxoff interrupt");
		}
	}

}

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {
	public static void main(String[] args) throws InterruptedException {
		ExecutorService exec = Executors.newCachedThreadPool();
		Car car=new Car();
		exec.execute(new WaxOff(car));
		exec.execute(new WaxOn(car));
		TimeUnit.MILLISECONDS.sleep(10);
		exec.shutdownNow();
	}
}

生产者消费者与队列

public class Task implements Runnable {

	@Override
	public void run() {
		System.out.println("runing");
	}

}
import java.util.concurrent.BlockingQueue;
public class TaskRunner implements Runnable {
	private BlockingQueue<Task> tasks;

	public void addTask(Task task) {
		try {
			tasks.put(task);
		} catch (InterruptedException e) {
			System.out.println("task put interrupt");
		}
	}

	public TaskRunner(BlockingQueue<Task> tasks) {
		super();
		this.tasks = tasks;
	}

	@Override
	public void run() {
		try {
			while (!Thread.interrupted()) {
				Task task = tasks.take();
				task.run();
			}
		} catch (InterruptedException e) {
			System.out.println("runner interrupt");
		}
		System.out.println("exiting runner run");
	}

}
public class QueueTest {
	static void test(String msg, BlockingQueue<Task> tasks) {
		TaskRunner runner = new TaskRunner(tasks);
		Thread t = new Thread(runner);
		t.start();
		for (int i = 0; i < 5; i++) {
			runner.addTask(new Task());
		}
		try {
			TimeUnit.MILLISECONDS.sleep(500);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("start interupt");
		t.interrupt();
		System.out.println("after interrupt");
	}

	public static void main(String[] args) {
		test("LinkedBlockingQueue", new LinkedBlockingQueue<>());
		test("ArrayBlockingQueue", new ArrayBlockingQueue<>(5));
		test("synchronousQueue",new SynchronousQueue<>());
	}
}
runing
runing
runing
runing
runing
start interupt
after interrupt
runner interrupt
exiting runner run
runing
runing
runing
runing
runing
start interupt
runner interrupt
exiting runner run
after interrupt
runing
runing
runing
runing
runing
start interupt
after interrupt
runner interrupt
exiting runner run

BlockingQueue 介绍

前言:
在新增的Concurrent包中,BlockingQueue很好的解决了多线程中,如何高效安全“传输”数据的问题。通过这些高效并且线程安全的队列类,为我们快速搭建高质量的多线程程序带来极大的便利。本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景。
认识BlockingQueue阻塞队列.

从上图我们可以很清楚看到,通过一个共享的队列,可以使得数据由队列的一端输入,从另外一端输出;
常用的队列主要有以下两种:(当然通过不同的实现方式,还可以延伸出很多不同类型的队列,DelayQueue就是其中的一种)
  先进先出(FIFO):先插入的队列的元素也最先出队列,类似于排队的功能。从某种程度上来说这种队列也体现了一种公平性。
  后进先出(LIFO):后插入队列的元素最先出队列,这种队列优先处理最近发生的事件。

  多线程环境中,通过队列可以很容易实现数据共享,比如经典的“生产者”和“消费者”模型中,通过队列可以很便利地实现两者之间的数据共享。假设我们有若干生产者线程,另外又有若干个消费者线程。如果生产者线程需要把准备好的数据共享给消费者线程,利用队列的方式来传递数据,就可以很方便地解决他们之间的数据共享问题。但如果生产者和消费者在某个时间段内,万一发生数据处理速度不匹配的情况呢?理想情况下,如果生产者产出数据的速度大于消费者消费的速度,并且当生产出来的数据累积到一定程度的时候,那么生产者必须暂停等待一下(阻塞生产者线程),以便等待消费者线程把累积的数据处理完毕,反之亦然。然而,在concurrent包发布以前,在多线程环境下,我们每个程序员都必须去自己控制这些细节,尤其还要兼顾效率和线程安全,而这会给我们的程序带来不小的复杂度。好在此时,强大的concurrent包横空出世了,而他也给我们带来了强大的BlockingQueue。(在多线程领域:所谓阻塞,在某些情况下会挂起线程(即阻塞),一旦条件满足,被挂起的线程又会自动被唤醒)

下面两幅图演示了BlockingQueue的两个常见阻塞场景:
       如上图所示:当队列中没有数据的情况下,消费者端的所有线程都会被自动阻塞(挂起),直到有数据放入队列。

   如上图所示:当队列中填满数据的情况下,生产者端的所有线程都会被自动阻塞(挂起),直到队列中有空的位置,线程被自动唤醒。
这也是我们在多线程环境下,为什么需要BlockingQueue的原因。作为BlockingQueue的使用者,我们再也不需要关心什么时候需要阻塞线程,什么时候需要唤醒线程,因为这一切BlockingQueue都给你一手包办了。既然BlockingQueue如此神通广大,让我们一起来见识下它的常用方法:
BlockingQueue的核心方法:
放入数据:
  offer(anObject):表示如果可能的话,将anObject加到BlockingQueue里,即如果BlockingQueue可以容纳,
    则返回true,否则返回false.(本方法不阻塞当前执行方法的线程)
  offer(E o, long timeout, TimeUnit unit),可以设定等待的时间,如果在指定的时间内,还不能往队列中
    加入BlockingQueue,则返回失败。
  put(anObject):把anObject加到BlockingQueue里,如果BlockQueue没有空间,则调用此方法的线程被阻断
    直到BlockingQueue里面有空间再继续.
获取数据:
  poll(time):取走BlockingQueue里排在首位的对象,若不能立即取出,则可以等time参数规定的时间,
    取不到时返回null;
  poll(long timeout, TimeUnit unit):从BlockingQueue取出一个队首的对象,如果在指定时间内,
    队列一旦有数据可取,则立即返回队列中的数据。否则知道时间超时还没有数据可取,返回失败。
  take():取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到
    BlockingQueue有新的数据被加入;
  drainTo():一次性从BlockingQueue获取所有可用的数据对象(还可以指定获取数据的个数),
    通过该方法,可以提升获取数据效率;不需要多次分批加锁或释放锁。
常见BlockingQueue
在了解了BlockingQueue的基本功能后,让我们来看看BlockingQueue家庭大致有哪些成员?

BlockingQueue成员详细介绍

  1. ArrayBlockingQueue
    基于数组的阻塞队列实现,在ArrayBlockingQueue内部,维护了一个定长数组,以便缓存队列中的数据对象,这是一个常用的阻塞队列,除了一个定长数组外,ArrayBlockingQueue内部还保存着两个整形变量,分别标识着队列的头部和尾部在数组中的位置。
      ArrayBlockingQueue在生产者放入数据和消费者获取数据,都是共用同一个锁对象,由此也意味着两者无法真正并行运行,这点尤其不同于LinkedBlockingQueue;按照实现原理来分析,ArrayBlockingQueue完全可以采用分离锁,从而实现生产者和消费者操作的完全并行运行。Doug Lea之所以没这样去做,也许是因为ArrayBlockingQueue的数据写入和获取操作已经足够轻巧,以至于引入独立的锁机制,除了给代码带来额外的复杂性外,其在性能上完全占不到任何便宜。 ArrayBlockingQueue和LinkedBlockingQueue间还有一个明显的不同之处在于,前者在插入或删除元素时不会产生或销毁任何额外的对象实例,而后者则会生成一个额外的Node对象。这在长时间内需要高效并发地处理大批量数据的系统中,其对于GC的影响还是存在一定的区别。而在创建ArrayBlockingQueue时,我们还可以控制对象的内部锁是否采用公平锁,默认采用非公平锁。

  2. LinkedBlockingQueue
    基于链表的阻塞队列,同ArrayListBlockingQueue类似,其内部也维持着一个数据缓冲队列(该队列由一个链表构成),当生产者往队列中放入一个数据时,队列会从生产者手中获取数据,并缓存在队列内部,而生产者立即返回;只有当队列缓冲区达到最大值缓存容量时(LinkedBlockingQueue可以通过构造函数指定该值),才会阻塞生产者队列,直到消费者从队列中消费掉一份数据,生产者线程会被唤醒,反之对于消费者这端的处理也基于同样的原理。而LinkedBlockingQueue之所以能够高效的处理并发数据,还因为其对于生产者端和消费者端分别采用了独立的锁来控制数据同步,这也意味着在高并发的情况下生产者和消费者可以并行地操作队列中的数据,以此来提高整个队列的并发性能。
    作为开发者,我们需要注意的是,如果构造一个LinkedBlockingQueue对象,而没有指定其容量大小,LinkedBlockingQueue会默认一个类似无限大小的容量(Integer.MAX_VALUE),这样的话,如果生产者的速度一旦大于消费者的速度,也许还没有等到队列满阻塞产生,系统内存就有可能已被消耗殆尽了。

ArrayBlockingQueue和LinkedBlockingQueue是两个最普通也是最常用的阻塞队列,一般情况下,在处理多线程间的生产者消费者问题,使用这两个类足以。

  1. DelayQueue
    DelayQueue中的元素只有当其指定的延迟时间到了,才能够从队列中获取到该元素。DelayQueue是一个没有大小限制的队列,因此往队列中插入数据的操作(生产者)永远不会被阻塞,而只有获取数据的操作(消费者)才会被阻塞。
    使用场景:
      DelayQueue使用场景较少,但都相当巧妙,常见的例子比如使用一个DelayQueue来管理一个超时未响应的连接队列。

  2. PriorityBlockingQueue
    基于优先级的阻塞队列(优先级的判断通过构造函数传入的Compator对象来决定),但需要注意的是PriorityBlockingQueue并不会阻塞数据生产者,而只会在没有可消费的数据时,阻塞数据的消费者。因此使用的时候要特别注意,生产者生产数据的速度绝对不能快于消费者消费数据的速度,否则时间一长,会最终耗尽所有的可用堆内存空间。在实现PriorityBlockingQueue时,内部控制线程同步的锁采用的是公平锁。

  3. SynchronousQueue
    一种无缓冲的等待队列,类似于无中介的直接交易,有点像原始社会中的生产者和消费者,生产者拿着产品去集市销售给产品的最终消费者,而消费者必须亲自去集市找到所要商品的直接生产者,如果一方没有找到合适的目标,那么对不起,大家都在集市等待。相对于有缓冲的BlockingQueue来说,少了一个中间经销商的环节(缓冲区),如果有经销商,生产者直接把产品批发给经销商,而无需在意经销商最终会将这些产品卖给那些消费者,由于经销商可以库存一部分商品,因此相对于直接交易模式,总体来说采用中间经销商的模式会吞吐量高一些(可以批量买卖);但另一方面,又因为经销商的引入,使得产品从生产者到消费者中间增加了额外的交易环节,单个产品的及时响应性能可能会降低。
      声明一个SynchronousQueue有两种不同的方式,它们之间有着不太一样的行为。公平模式和非公平模式的区别:
      如果采用公平模式:SynchronousQueue会采用公平锁,并配合一个FIFO队列来阻塞多余的生产者和消费者,从而体系整体的公平策略;
      但如果是非公平模式(SynchronousQueue默认):SynchronousQueue采用非公平锁,同时配合一个LIFO队列来管理多余的生产者和消费者,而后一种模式,如果生产者和消费者的处理速度有差距,则很容易出现饥渴的情况,即可能有某些生产者或者是消费者的数据永远都得不到处理。
    小结
      BlockingQueue不光实现了一个完整队列所具有的基本功能,同时在多线程环境下,他还自动管理了多线间的自动等待于唤醒功能,从而使得程序员可以忽略这些细节,关注更高级的功能。

吐司 BlockingQuueue 示例:
这样的业务场景: 两个机器 一个生产吐司一个给吐司涂黄油 我们可以通过BlockingQueue来实现线程间的协作。

public class Toast {
	 enum STATUS {
		ORIGIN, MAKED, OILED, JAMED
	}

	private STATUS status = STATUS.ORIGIN;
	 final int id;

	public Toast(int id) {
		super();
		this.id = id;
	}

	@Override
	public String toString() {
		return "Toast [id=" + id + "]";
	}

	public void maked() {
		status = STATUS.MAKED;
	}

	public void oiled() {
		status = STATUS.OILED;
	}

	public void jemed() {
		status = STATUS.JAMED;
	}

	public STATUS getStatus() {
		return status;
	}
}
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class Maker implements Runnable {
	private int id = 0;
	private LinkedBlockingQueue<Toast> makeQueue;

	public Maker(LinkedBlockingQueue<Toast> makeQueue) {
		super();
		this.makeQueue = makeQueue;
	}

	@Override
	public void run() {
		try {
			while (!Thread.interrupted()) {
				Toast toast = new Toast(++id);
				toast.maked();
				TimeUnit.MILLISECONDS.sleep(100);
				System.out.println("maked toast:" + toast);
				makeQueue.put(toast); // 阻塞方法
			}
		} catch (InterruptedException e) {
			System.out.println("maker interrupt");
		}
	}

}
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class Oiler implements Runnable {
	private LinkedBlockingQueue<Toast> makeQueue;
	private LinkedBlockingQueue<Toast> oilQueue;

	public Oiler(LinkedBlockingQueue<Toast> makeQueue, LinkedBlockingQueue<Toast> oilQueue) {
		super();
		this.makeQueue = makeQueue;
		this.oilQueue = oilQueue;
	}

	@Override
	public void run() {
		try {
			while (!Thread.interrupted()) {
				Toast toast = makeQueue.take();// 阻塞方法
				toast.oiled();
				TimeUnit.MILLISECONDS.sleep(50);
				System.out.println("oil toast:" + toast);
				oilQueue.put(toast);
			}
		} catch (InterruptedException e) {
			System.out.println("oiler interrupt");
		}
	}

}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class Eater implements Runnable {
	private LinkedBlockingQueue<Toast> oilQueue;
	private int count = 0;

	public Eater(LinkedBlockingQueue<Toast> oilQueue) {
		super();
		this.oilQueue = oilQueue;
	}

	@Override
	public void run() {
		try {
			while (!Thread.interrupted()) {
				Toast toast = oilQueue.take();
				System.out.println("eater eat:" + toast);
				count++;
				if (toast.getStatus() != Toast.STATUS.OILED || count != toast.id) {
					System.out.println("error:" + toast);
				}
			}
		} catch (InterruptedException e) {
			System.out.println("eater interrupt");
		}
	}

	public static void main(String[] args) throws InterruptedException {
		ExecutorService exec = Executors.newCachedThreadPool();
		LinkedBlockingQueue<Toast> makeQueue = new LinkedBlockingQueue<>();
		LinkedBlockingQueue<Toast> oilQueue = new LinkedBlockingQueue<>();
		exec.execute(new Maker(makeQueue));
		exec.execute(new Oiler(makeQueue, oilQueue));
		exec.execute(new Eater(oilQueue));
		TimeUnit.MILLISECONDS.sleep(1000);
		exec.shutdownNow();
	}
}
maked toast:Toast [id=1]
oil toast:Toast [id=1]
eater eat:Toast [id=1]
maked toast:Toast [id=2]
oil toast:Toast [id=2]
eater eat:Toast [id=2]
maked toast:Toast [id=3]
oil toast:Toast [id=3]
eater eat:Toast [id=3]
maked toast:Toast [id=4]
oil toast:Toast [id=4]
eater eat:Toast [id=4]
maked toast:Toast [id=5]
oil toast:Toast [id=5]
eater eat:Toast [id=5]
maked toast:Toast [id=6]
oil toast:Toast [id=6]
eater eat:Toast [id=6]
maked toast:Toast [id=7]
oil toast:Toast [id=7]
eater eat:Toast [id=7]
maked toast:Toast [id=8]
oil toast:Toast [id=8]
eater eat:Toast [id=8]
maked toast:Toast [id=9]
oil toast:Toast [id=9]
eater eat:Toast [id=9]
oiler interrupt
maker interrupt
eater interrupt

任务之间通过管道输入输出
通过输入输出在线程之间通信通常很有用,提供线程功能的类库一“管道”的形式对线程间的输入、输出提供了支持。他们在java中输入、输出类库中的对应物就是PipedWriter(允许向任意管道写)和PipedReader(允许不同任务向同一管道读)。这个模型可以看做是“生产者-消费者”的变体这里的管道就是封装好的一个方案。管道基本上是一个阻塞队列,存在于多个引入BlockingQueue之前的版本。
下面是一个使用管道通信的例子:


import java.io.IOException;
import java.io.PipedWriter;
import java.util.concurrent.TimeUnit;

public class Sender implements Runnable {
	private PipedWriter send = new PipedWriter();

	public PipedWriter getSend() {
		return send;
	}

	@Override
	public void run() {
		try {
			while (true) {
				for (char a = 'a'; a < 'z'; a++) {
					TimeUnit.MILLISECONDS.sleep(500);
					send.write(a);
				}
			}
		} catch (IOException e) {
			System.out.println("send ioexception");
		} catch (InterruptedException ie) {
			System.out.println("send interruptedException");
		}
	}

}

import java.io.IOException;
import java.io.PipedReader;

public class Receiver implements Runnable {
	private Sender sender;
	private PipedReader receive;

	public Receiver(Sender sender) {
		super();
		this.sender = sender;
		try {
			receive = new PipedReader(sender.getSend());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			while (true) {
				char temp = (char) receive.read(); // block
				System.out.println("read: "+temp);
			}
		} catch (IOException e) {
			System.out.println("resceiver ioexception");
		}
	}

}

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {
	public static void main(String[] args) throws Exception {
		ExecutorService exec = Executors.newCachedThreadPool();
		Sender sender = new Sender();
		Receiver receiver = new Receiver(sender);
		exec.execute(sender);
		exec.execute(receiver);
		TimeUnit.MILLISECONDS.sleep(5000);
		exec.shutdownNow();
	}
}
read: a
read: b
read: c
read: d
read: e
read: f
read: g
read: h
read: i
read: j
resceiver ioexception
send interruptedException

PipedReader 调用 read() 时,如果没有更多数据,它将阻塞。
注意 在不同的平台上 管道可能产生不一致的行为(BlockingQueue使用起来更健壮更容易)

原文地址:https://www.cnblogs.com/joeCqupt/p/6845633.html