生产商模型代码
public class develop implements Runnable{
//创建构造方法
public develop(Object obj){
this.obj = obj;
}
Object obj;
int count = 1;
boolean judge = true;
@Override
public void run() {
while(true){
synchronized (obj){
if(judge == false){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("生产完成第"+count+"件商品");
judge = true;
count++;
obj.notify();
}
else{
try {
//线程等待
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("下一个顾客来了!");
judge = false;
}
}
}
}
}
消费者模型代码
public class customer implements Runnable{
Object obj;
boolean judge = false;
public customer(Object obj){
this.obj = obj;
}
@Override
public void run() {
while(true){
synchronized (obj){
if(judge){
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("我拿走商品了,谢谢");
judge = false;
}
else {
//唤醒另一个线程
obj.notify();
judge = true;
}
}
}
}
}
主方法
public class Test {
public static void main(String[] args) {
develop dp = new develop(5);
customer cs = new customer(5);
Thread t0 = new Thread(dp);
Thread t1 = new Thread(cs);
t0.start();
t1.start();
}
}
以上是我学习java多线程时自己写的实现生产者-消费者模型功能代码,有啥问题可以改进都可以提出来一起交流一下~