线程通信
- 应用场景:生产者和消费者问题
- 假设仓库中只能存放一件产品,生产者将生产出来的产品放入仓库.消费者将仓库中产品取走消费.
- 如果仓库中没有产品,则生产者将产品放入仓库﹐否则停止生产并等待,直到仓库中的产品被消费者取走为止.
- 如果仓库中放有产品﹐则消费者可以将产品取走消费,否则停止消费并等待,直到仓库中再次放入产品为止.
管程法
package gaoji;
public class TestPC {
public static void main(String[] args) {
synContainer synContainer = new synContainer();
scz scz = new scz(synContainer);
xfz xfz = new xfz(synContainer);
scz.start();
xfz.start();
}
}
class scz extends Thread{
synContainer synContainer;
public scz (synContainer synContainer){
this.synContainer=synContainer;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
synContainer.push(new Chicken(i));
System.out.println("产生了"+i+"只鸡");
}
}
}
class xfz extends Thread{
synContainer synContainer;
public xfz (synContainer synContainer){
this.synContainer=synContainer;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
synContainer.pop();
System.out.println("消费了第"+i+"只鸡");
}
}
}
class Chicken {
int id;
public Chicken(int id) {
this.id = id;
}
}
class synContainer{
Chicken[] chickens = new Chicken[10];
int count=0;
public synchronized void push(Chicken chicken){
if(count==10){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
chickens[count] = chicken;
count++;
this.notifyAll();
}
public synchronized Chicken pop(){
if(count==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
Chicken chicken = chickens[count];
this.notifyAll();
return chicken;
}
}
信号灯法
package gaoji;
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Look(tv).start();
}
}
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){
tv.by("大本营");
}else {
tv.by("douyin");
}
}
}
}
class Look extends Thread{
TV tv;
public Look(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.gk();
}
}
}
class TV {
String name;
boolean flag=true;
public synchronized void by(String name){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了"+name);
this.notifyAll();
this.name = name;
this.flag= !this.flag;
}
public synchronized void gk(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了"+name);
this.notifyAll();
this.flag= !this.flag;
}
}