码迷,mamicode.com
首页 > 编程语言 > 详细

5.17 JAVA

时间:2016-05-17 13:32:45      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

class Computer{
int num=0;
boolean flag=false;
public synchronized void set(){
if(flag){
try{
super.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
num++;
System.out.println("生产了第"+num+"台电脑。");
flag=true;
super.notify();
}
public synchronized void get(){
if(!flag){
try{
super.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("取走了第"+num+"台电脑。");
flag=false;
super.notify();
}
}
class Customer implements Runnable{
private Computer com;

public void setCompu(Computer compu){
this.com=compu;
}
public Computer getCompu(){
return this.com;
}
public Customer(Computer com){
this.com=com;
}
public void run(){
for(int i=0;i<10;i++){
com.set();
com.get();
}
}
}
public class Test9_2 {
public static void main(String[] args) {
Computer a=new Computer();
Customer cus=new Customer(a);
new Thread(cus).start();
}
}

技术分享

5.17 JAVA

标签:

原文地址:http://www.cnblogs.com/coolye/p/5501057.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!