JAVA多线程通信之流水线
上道工序为:生产手机主板,下道工序为:利用刚生产的主板,组装成手机。
通过多线程的通信进行类之间的函数的相互调用,建立了两个线程,生产手机主板的流水线MadeBoard线程和消费主板组装成手机的流水线MadePhone线程
//Product类,产品类
public class Product {
String name;
int count=100;
boolean flag = true;
public synchronized void set(String name) {
if(!flag) {
try {
this.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.name = name;
System.out.println("已生产了主板第"+name);
this.notify();
flag = false;
}
public synchronized void get() {
if(flag) {
try {
this.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("已组装了手机第"+name);
this.notifyAll();
flag = true;
}
}
//MadeBoard类,生产主板
public class MadeBoard implements Runnable{
private Product product ;
public MadeBoard(Product m ) {
super();
this.product = m;
}
public void run() {
for(int i = 0; i < product.count; i++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i % 2 == 0) {
product.set(i+1+"号");
}
else {
product.set(i+1+"号");
}
}
}
}
//MadePhone类,组装成手机
public class MadePhone implements Runnable{
private Product product ;
public MadePhone(Product product ) {
super();
this.product = product;
}
public void run() {
for(int i = 0; i <product.count; i++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
product.get();
}
}
}
//测试类
public class test {
public static void main(String[] args) {
Product m = new Product();
MadeBoard player = new MadeBoard(m);
MadePhone viewer = new MadePhone(m);
Thread thread1 = new Thread(player);
Thread thread2 = new Thread(viewer);
thread1.start();
thread2.start();
}
}
我的GitHub链接https://github.com/TYduoduo
喜欢的朋友记得点赞关注哦
来源:CSDN
作者:生姜用户
链接:https://blog.csdn.net/qq_45514303/article/details/104114907