求大佬帮忙编写一个java程序。越简单越好
发布网友
发布时间:2022-04-29 03:40
我来回答
共2个回答
热心网友
时间:2023-10-09 13:37
按照题目要求编写的生产者消费者模式的Java程序如下
//生产者-消费者模式
public class ThreadDemo {
public static void main(String[] args) {
Store s=new Store(10);
Thread t1=new Procer( "procer1 ",s);
Thread t2=new Consumer( "consumer1 ",s);
t1.start();
t2.start();
}
}
//生产者类
class Procer extends Thread {
private String name;
private Store s;
public Procer(String name, Store s) {
this.name = name;
this.s = s;
}
public void run() {
while (true) {
s.push(name);
}
}
}
//消费者类
class Consumer extends Thread {
private String name;
private Store s;
public Consumer(String name, Store s) {
this.name = name;
this.s = s;
}
public void run() {
while (true) {
s.pop(name);
}
}
}
//仓库类
class Store {
private final int size;
private int count;
public Store(int size) {
this.size = size;
}
public synchronized void push(String name) {
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (count == this.size) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count++;
System.out.println(name + " proce " + count);
this.notify();
}
public synchronized void pop(String name) {
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (count == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name + " consume " + count);
count--;
this.notify();
}
}
热心网友
时间:2023-10-09 13:38
私聊我,写好发你
热心网友
时间:2023-10-09 13:37
按照题目要求编写的生产者消费者模式的Java程序如下
//生产者-消费者模式
public class ThreadDemo {
public static void main(String[] args) {
Store s=new Store(10);
Thread t1=new Procer( "procer1 ",s);
Thread t2=new Consumer( "consumer1 ",s);
t1.start();
t2.start();
}
}
//生产者类
class Procer extends Thread {
private String name;
private Store s;
public Procer(String name, Store s) {
this.name = name;
this.s = s;
}
public void run() {
while (true) {
s.push(name);
}
}
}
//消费者类
class Consumer extends Thread {
private String name;
private Store s;
public Consumer(String name, Store s) {
this.name = name;
this.s = s;
}
public void run() {
while (true) {
s.pop(name);
}
}
}
//仓库类
class Store {
private final int size;
private int count;
public Store(int size) {
this.size = size;
}
public synchronized void push(String name) {
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (count == this.size) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count++;
System.out.println(name + " proce " + count);
this.notify();
}
public synchronized void pop(String name) {
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (count == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name + " consume " + count);
count--;
this.notify();
}
}
热心网友
时间:2023-10-09 13:38
私聊我,写好发你