java多线程的案例,给我学习一下,谢谢!
发布网友
发布时间:2022-05-27 03:24
我来回答
共2个回答
热心网友
时间:2023-10-03 01:53
public class Consumer extends Thread{
private SharedData sd;
private char c;
public Consumer(SharedData sd) {
this.sd = sd;
}
public void run() {
do {
c = sd.consumer();
try {
Thread.sleep((long)Math.random()*3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (c != 'D');
}
}
public class Proctor extends Thread{
private SharedData sd;
public Proctor(SharedData sd) {
this.sd = sd;
}
public void run() {
for (char c='A';c<='D';c++) {
sd.proct(c);
try {
Thread.sleep((long)Math.random()*3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class SharedData {
private char c; //当前正在生产或消费的产品
private boolean isProcted = false;//是否已经生产
//生产产品
public synchronized void proct(char c) {
if (isProcted) {
//已经生产,等待消费
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.c = c;
System.out.println("生产产品" + c);
this.isProcted = true;//已经生产
notify(); //通知消费者
}
//消费产品
public synchronized char consumer() {
if (!isProcted) { //未生产,则等待生产产品
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("消费产品" + c);
isProcted = false;
notify();
return this.c;
}
}
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
SharedData sd = new SharedData();
Proctor p = new Proctor(sd);
Consumer c = new Consumer(sd);
c.start();
p.start();
}
}
热心网友
时间:2023-10-03 01:53
我觉得技视网就很不错,在IT这一块做得很纯粹,网站根据不同的IT领域划分了不同的关键词进行搜索学习,而且都是免费的在线视频,你感兴趣可以去看看,反正我经常去那里学习,希望对你有帮助!