线程通信
多线程协同工作时需要通信,通信的方法
管程法
* @PackageName:Threadtest
* @ClassName:pro_com_tee
* @Description:使用管程法解决消费者与生产者的通信协作问题
* @date 2021/8/12 9:05
*/
public class pro_com_tee {
public static void main(String[] args) {
Container container = new Container();
new producer(container).start();
new consumer(container).start();
}
static 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 Tea(i));
System.out.println("生产了"+i+"杯奶茶");
}
}
}
static 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+"杯奶茶");
}
}
}
static class Tea {
int id;
public Tea(int id) {
this.id = id;
}
}
static class Container {
Tea[] teas = new Tea[10];
int count = 0;
//生产
public synchronized void push(Tea tea){
//判断容器是否满了
if (count==teas.length) {
//等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
teas[count]=tea;
count++;
//通知消费者消费
this.notifyAll();
}
//消费
public synchronized Tea pop(){
//判断容器是否为空
if (count==0){
//等待,通知生产者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
Tea tea= teas[count];
//消费了,可以生产了
this.notifyAll();
return tea;
}
}
信号灯法
通过标志位的变化来改变进程的状态来避免协作问题
线程池
* @PackageName:Threadtest
* @ClassName:ThreadPool
* @Description:线程池的初级使用
* @date 2021/8/12 20:11
*/
public class ThreadPool {
public static void main(String[] args) {
//创建服务,创建线程池
//参数为池子大小
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());
}
}