并发编程(三)-线程协作

本文详细介绍了三种线程协作方式:wait/notify、condition及BlockingQueue的使用方法,并通过生产者消费者模式的具体实例展示了每种协作方式的特点和应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程协作指多个线程之间协调地交替执行,线程协作有两种方式:
1.wait/notify,notifyAll
该方法需要搭配synchronized关键字使用,wait(),notify(),notifyAll()必须在同步方法或者同步块中使用,否则会抛出IllegalMonitorStateException异常.注意notify(),notifyAll()只能唤醒在同一锁对象上的wait()线程.

下面是生产者或消费者的例子

public class Restaurant {
	public Meal meal;
	public Customer customer=new Customer(this);
	public Chef chef=new Chef(this);
	public ExecutorService exec=Executors.newCachedThreadPool();
	public Restaurant(){
		exec.execute(customer);
		exec.execute(chef);
	}
	public static void main(String[] args) {
		new Restaurant();
	}
}
class Meal{
	private final int orderNum;
	public Meal(int orderNum){
		this.orderNum=orderNum;
	}
	public String toString(){ return "Meal "+orderNum;}
}
class Customer implements Runnable{
	private Restaurant rest;
	public Customer(Restaurant rest){
		this.rest=rest;
	}
	public void run(){
		try{
			while(!Thread.interrupted()){
				synchronized(this){
					while(rest.meal==null){
						wait();
					}
					System.out.println("customer got "+rest.meal);
				}
				synchronized(rest.chef){
					rest.meal=null;
					rest.chef.notify();
				}
			}
		}
		catch(InterruptedException ex){
			System.out.println("customer interrupted");
		}
	}
}
class Chef implements Runnable{
	private Restaurant rest;
	private int count=0;
	public Chef(Restaurant rest){
		this.rest=rest;
	}
	public void run(){
		try{
			while(!Thread.interrupted()){
				synchronized(this){
					while(rest.meal!=null){
						wait();
					}
				}
				if(count++==10){
					System.out.println("Out of Food!");
					rest.exec.shutdownNow();
				}
				System.out.println("order up!");
				synchronized(rest.customer){
					rest.meal=new Meal(count);
					rest.customer.notify();
				}
				TimeUnit.MILLISECONDS.sleep(100);
			}
		}catch(InterruptedException e){
			System.out.println("chef interrupted");
		}
	}
}
输出:
order up!
customer got Meal 1
order up!
customer got Meal 2
order up!
customer got Meal 3
order up!
customer got Meal 4
order up!
customer got Meal 5
order up!
customer got Meal 6
order up!
customer got Meal 7
order up!
customer got Meal 8
order up!
customer got Meal 9
order up!
customer got Meal 10
Out of Food!
order up!
customer interrupted
chef interrupted
2.condition.await(),condition.signal(),condition.signalAll()
需要搭配Lock进行使用,使用起来更加复杂;使用condition实现生产者和消费者的例子,注意signal()signalAll()只能唤醒同一个lock下,同一个condition上的await()线程;可以看到,使用condition实现更加复杂
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Restaurant {
	Meal meal;
	Customer customer=new Customer(this);
	Chef chef=new Chef(this);
	ExecutorService exec=Executors.newCachedThreadPool();
	public Restaurant(){
		exec.execute(customer);
		exec.execute(chef);
	}
	public static void main(String[] args) {
		new Restaurant();
	}
}
class Meal{
	private int orderNum;
	public Meal(int orderNum){
		this.orderNum=orderNum;
	}
	public String toString(){
		return "Meal "+orderNum;
	}
}
class Customer implements Runnable{
	Restaurant rest;
	public Customer(Restaurant rest){
		this.rest=rest;
	}
	public Lock lock=new ReentrantLock();
	public Condition condition=lock.newCondition();
	public void run(){
		try{
			while(!Thread.interrupted())
			{
				lock.lock();
				try{
					while(rest.meal==null){
						condition.await();
					}
				}finally{
					lock.unlock();
				}
				
				System.out.println("Customer get "+rest.meal);
				rest.meal=null;
				rest.chef.lock.lock();
				
				try{
					rest.chef.condition.signalAll();
				}finally{
					rest.chef.lock.unlock();
				}
			}
		}catch(InterruptedException ex){
			System.out.println("Customer is interrupted!");
		}
	}
}
class Chef implements Runnable{
	Restaurant rest;
	public Chef(Restaurant rest){
		this.rest=rest;
	}
	public Lock lock=new ReentrantLock();
	public Condition condition=lock.newCondition();
	private int count=0;
	public void run(){	
		try{
			while(!Thread.interrupted()){
				lock.lock();
				try{
					while(rest.meal!=null){
						condition.await();
					}
				}finally{
					lock.unlock();
				}
				
				if(++count==10){
					System.out.println("out of food!");
					rest.exec.shutdownNow();
				}
				rest.meal=new Meal(count);
				rest.customer.lock.lock();
				try{
					rest.customer.condition.signalAll();
				}finally{
					rest.customer.lock.unlock();
				}
				System.out.println("Order up!");
				TimeUnit.MILLISECONDS.sleep(300);
			}
		}catch(InterruptedException ex){
			System.out.println("Chef is interrupted!");
		}
	}
}
3.BlockingQueue<T>
常用的BlockQueue接口实现由ArrayBlockQueue和LinkedBlockingQueue,以下使用容量为1的LinkedBlockQueue实现

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

public class Restaurant {
	Meal meal;
	Customer customer=new Customer(this);
	Chef chef=new Chef(this);
	BlockingQueue<Meal> queue=new LinkedBlockingDeque<Meal>(1);
	ExecutorService exec=Executors.newCachedThreadPool();
	public Restaurant(){
		exec.execute(customer);
		exec.execute(chef);
	}
	public static void main(String[] args) {
		new Restaurant();
	}
}
class Meal{
	private final int orderNum;
	public Meal(int orderNum){
		this.orderNum=orderNum;
	}
	public String toString(){ return "Meal "+orderNum;}
}
class Customer implements Runnable{
	private Restaurant rest;
	public Customer(Restaurant rest){
		this.rest=rest;
	}
	public void run(){
		try{
			while(!Thread.interrupted()){
				rest.meal=rest.queue.take();
				System.out.println("customer got "+rest.meal);
			}
		}
		catch(InterruptedException ex){
			System.out.println("customer interrupted");
		}
	}
}
class Chef implements Runnable{
	private Restaurant rest;
	private int count=0;
	public Chef(Restaurant rest){
		this.rest=rest;
	}
	public void run(){
		try{
			while(!Thread.interrupted()){
				if(++count==10){
					System.out.println("out of food!");
					rest.exec.shutdownNow();
				}
				rest.meal=new Meal(count);
				rest.queue.put(rest.meal);
				System.out.println("order up!");
				TimeUnit.MILLISECONDS.sleep(100);
			}
		}catch(InterruptedException e){
			System.out.println("chef interrupted");
		}
	}
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值