nchronized Chicken pop() {
//如果容器为空,就等待生产者生产
if (0 == cnt) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//通知生产者可以生产
this.notifyAll();
//如果没空,就取出产品
return chickens[--cnt];
}
}
class Chicken {
public int id;
public Chicken(int id) {
this.id = id;
}
}
模型2:
信号灯法代码实现
package thread.communication;
/**
* 生产者消费者问题2:信号灯法,标志位解决
*/
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Actor(tv).start();
new Watcher(tv).start();
}
}
//生产者:演员
class Actor extends Thread {
TV tv = new TV();
public Actor(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 Watcher extends Thread {
TV tv;
public Watcher(TV tv) {
this.tv = tv;
}
@Override
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.notifyAll();
this.voice = voice;
this.flag = !this.flag;
}
//观看
public synchronized void watch() {
if (flag)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("观众观看了:" + voice);
//通知演员表演
this.notifyAll();
this.flag = !this.flag;
}
}
注意点:线程间通信的前提是 线程同步,所以依然需要设置锁。
8.线程池
线程池概念
使用线程池
线程池代码实现
package thread.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 测试线程池
*/
public class TestPool {
public static void main(String[] args) {
//1.创建服务,创建线程池
//参数为线程大小
ExecutorService service = Executors.newFixedThreadPool(10);
//执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//关闭链接
service.shutdown();
}
}
class MyThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}