线程协作
生产者消费者模式
- Java提供了几个方法解决线程之间的通信问题
wait(): 表示线程会一直等待,直到其他线程通知,与sleep不同,会释放锁;
wait(long timeout)
notify():唤醒一个处于等待状态的线程;
notifyAll():唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调度
管程法:
public class PAC {
public static void main(String[] args) {
Container container = new Container();
Producer producer = new Producer(container);
Consumer consumer = new Consumer(container);
producer.start();
consumer.start();
}
}
class Chicken{
int id;
public Chicken(int id){
this.id = id;
}
}
class Container{
Chicken[] chickens = new Chicken[10];
int count = 0;
public synchronized void push(Chicken chicken) throws InterruptedException {
if (count == chickens.length){
this.wait();
}
chickens[count] = chicken;
count++;
this.notify();
}
public synchronized Chicken take() throws InterruptedException {
if (count == 0){
this.wait();
}
count--;
Chicken chicken = chickens[count];
this.notifyAll();
return chicken;
}
}
class Producer extends Thread{
Container container;
public Producer(Container container){
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("生产了"+i+"只鸡");
try {
container.push(new Chicken(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer extends Thread{
Container container;
public Consumer(Container container){
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
System.out.println("消费了" + container.take().id + "只鸡");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
信号灯法:
public class PAC2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
class Watcher extends Thread{
TV tv;
public Watcher(TV tv){
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
try {
tv.watch();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Player extends Thread{
TV tv;
public Player(TV tv){
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i%2 == 0){
this.tv.play("快乐大本营");
}else {
this.tv.play("广告");
}
}
}
}
class TV{
String voice;
boolean flag = false; //没节目
public synchronized void play(String voice){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.voice = voice;
this.notifyAll();
System.out.println("演员表演了" + voice);
this.flag = !this.flag;
}
public synchronized void watch() throws InterruptedException {
System.out.println("观众观看了" + voice);
if (!flag){
this.wait();
}
System.out.println("观众观看了" + voice);
this.notifyAll();
this.flag = !this.flag;
}
}