线程通信
使用wait()、notify()或者notifyAll()实现线程通信
解决方式1:管程法
并发协作模型“生产者/消费者模式”——>管程法生产者:负责生产数据的模块(这里的模块可能是:方法、对象、线程、进程)消费者:负责处理数据的模块(这里的模块可能是:方法、对象、线程、进程)缓冲区:消费者不能直接使用生产者的数据,它们之间有个“缓冲区”;生产者将生产好的数据放入“缓冲区”,消费者从“缓冲区”拿要处理的数据。
package com
.study
.cooperation
;
public class CoTest01 {
public static void main(String
[] args
) {
SynContainer container
= new SynContainer();
new Productor(container
).start();
new Consumer(container
).start();
}
}
class Productor extends Thread{
SynContainer container
;
public Productor(SynContainer container
) {
this.container
= container
;
}
public void run() {
for (int i
= 1; i
<= 100; i
++) {
System
.out
.println("生产——>第"+i
+"个");
container
.push(new Steamedbun(i
));
}
}
}
class Consumer extends Thread{
SynContainer container
;
public Consumer(SynContainer container
) {
this.container
= container
;
}
public void run() {
for (int i
= 1; i
<= 100; i
++) {
System
.out
.println("消费——>第"+container
.pop().id
+"个");
}
}
}
class SynContainer{
Steamedbun
[] buns
= new Steamedbun[10];
int count
= 0;
public synchronized void push(Steamedbun bun
) {
if (count
== buns
.length
) {
try {
this.wait();
} catch (InterruptedException e
) {
e
.printStackTrace();
}
}
buns
[count
]=bun
;
count
++;
this.notifyAll();
}
public synchronized Steamedbun
pop() {
if (count
== 0) {
try {
this.wait();
} catch (InterruptedException e
) {
e
.printStackTrace();
}
}
count
--;
Steamedbun bun
= buns
[count
];
this.notifyAll();
return bun
;
}
}
class Steamedbun{
int id
;
public Steamedbun(int id
) {
this.id
= id
;
}
}
解决方式2:信号灯法
并发协作模型“生产者/消费者模式”——>信号灯法使用标志切换
package com
.study
.cooperation
;
public class CoTest02 {
public static void main(String
[] args
) {
Tv tv
= new Tv();
new Player(tv
).start();
new Watcher(tv
).start();
}
}
class Player extends Thread{
Tv tv
;
public Player(Tv tv
) {
super();
this.tv
= tv
;
}
public void run() {
for (int i
= 0; i
< 20; i
++) {
if (i
% 2 == 0) {
this.tv
.play("电影");
} else {
this.tv
.play("广告");
}
}
}
}
class Watcher extends Thread{
Tv tv
;
public Watcher(Tv tv
) {
super();
this.tv
= tv
;
}
public void run() {
for (int i
= 0; i
< 20; i
++) {
tv
.watch();
}
}
}
class Tv{
String voice
;
boolean flag
= true;
public synchronized void play(String voice
) {
if (!flag
) {
try {
this.wait();
} catch (InterruptedException e
) {
e
.printStackTrace();
}
}
System
.out
.println("表演了:"+voice
);
this.voice
= voice
;
this.flag
= !flag
;
this.notifyAll();
}
public synchronized void watch() {
if (flag
== true) {
try {
this.wait();
} catch (InterruptedException e
) {
e
.printStackTrace();
}
}
System
.out
.println("听到了:"+voice
);
this.flag
= !flag
;
this.notifyAll();
}
}