线程合作线程通信
wait(); 线程等待 放锁
notify(); 唤醒一个处于等待状态的线程
解决方式:
-
生产着 把东西放在缓冲区
-
消费者从缓冲区拿东西
-
生产者和消费着之间不干涉
//利用缓存区
public class TestPC {
public static void main(String[] args) {
Container container = new Container();
new Producer(container).start();
new Consumer(container).start();
}
}
//生产者
class Producer extends Thread{
Container container;
public Producer(Container container){
this.container =container;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Production(i));
System.out.println("做好了 "+ (i+1) +"个");
}
}
}
//消费者
class Consumer extends Thread{
Container container;
public Consumer(Container container){
this.container =container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了 " + (container.pop().id+1)+" 个");
}
}
}
//商品
class Production{
int id;
public Production(int id) {
this.id = id;
}
}
//缓冲区
class Container{
//容器大小
Production[] productions = new Production[10];
//计数
int count =0 ;
//生产者放入产品
public synchronized void push(Production production){
//如果容器满了 需要等待消费者
if (count==productions.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满 放入容器
productions[count]=production;
count++;
//通知可以消费了
this.notifyAll();
}
//消费者拿走产品
public synchronized Production pop(){
if (count==0){
//等待生产者生产 消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
Production production = productions[count];
//消费完了
this.notifyAll();
return production;
}
}
用flag 来完成 进程的等待和唤醒
public class TestPcFlag {
public static void main(String[] args) {
PlatForm platForm = new PlatForm(); //创建一个PlatForm对象
new Shower(platForm).start(); //将对象丢入线程构造器
new Watcher(platForm).start(); //将对象丢入线程构造器
}
}
class Shower extends Thread{
PlatForm platForm;
Shower(PlatForm platForm){ //构造器
this.platForm =platForm;
}
@Override
public void run(){ //重写run方法 运行10此 Platform类里的show方法
for (int i = 0; i < 10; i++) {
platForm.show(); //运行丢入Platform类里的show方法
}
}
}
class Watcher extends Thread{
PlatForm platForm;
Watcher(PlatForm platForm){ //构造器接受丢进来的 PlatForm 类
this.platForm =platForm;
}
@Override
public void run(){
for (int i = 0; i < 10; i++) {//重写run方法 运行10此 Platform类里的watch方法
platForm.watch(); //运行丢入Platform类里的watch方法
}
}
}
class PlatForm {
boolean flag =true; //设定一个flag 来判断 进程是否需要等待
public synchronized void show(){
if (!flag){ //如果flag 时false
try {
this.wait(); //等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("表演节目");
flag =!flag; //反转flag
this.notifyAll(); //唤醒其他等待的进程
}
public synchronized void watch(){
if (flag){ //如果flag 时ture
try {
this.wait(); //等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看节目");
flag =!flag; //反转flag
this.notifyAll(); //唤醒其他等待进程
}
}