生產電腦,取走電腦多執行緒
public class ThreadDemo{
public static void main(String[] args) {
Resource res = new Resource();
new Thread(new Productor(res)).start();
new Thread(new Consumer(res)).start();
}
}
class Computer{
private static int count = 0;
private String name;
private double price;
public Computer(String name,double price) {
this.name = name;
this.price = price;
count ++;
}
public String toString() {
return "第" + count + "臺電腦:" + this.name + "、價格:" + this.price;
}
}
class Resource{
private Computer computer;
private boolean flag = true;//true,要生產,不取走,false,不生產,要取走
public synchronized void product() {
if(this.flag == false) {
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.computer = new Computer("華碩筆記本",4998.00);
System.out.println("生產" + this.computer);
this.flag = false;
super.notifyAll();
}
public synchronized void get() {
if(this.flag == true) {
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("取走" + this.computer);
this.flag = true;
super.notifyAll();
}
}
class Productor implements Runnable{
private Resource resource;
public Productor(Resource resource) {
this.resource = resource;
}
public void proC() {
for(int x = 0;x < 50;x ++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.resource.product();
}
}
@Override
public void run() {
this.proC();
}
}
class Consumer implements Runnable{
private Resource resource;
public Consumer(Resource resource) {
this.resource = resource;
}
public void getC() {
for(int x = 0;x < 50;x ++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.resource.get();
}
}
@Override
public void run() {
this.getC();
}
}
同步鎖機制,生產與取走的切換,休眠的限制。