您的位置:首页 > 其它

多线程采用不同的方法操作一个资源的例子

2015-12-06 16:38 423 查看
资源类

两个不同的方法,都是同步方法,当一个线程调用一个同步方法时,另外一个线程是不能调用另一个同步方法。

要特别注意标记的操作。

notify()执行后,如果这个线程后面还是程序未执行完,要先执行完,才会让出对象的锁。

public class ResDemo {
private int num;
private boolean flag;
public ResDemo(int num, boolean flag) {
super();
this.num = num;
this.flag = flag;
}
public synchronized void pro(){
if(flag){
System.out.println("仓库有货,不用生产");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.flag=true;
this.num++;
System.out.println(Thread.currentThread().getName()+"生产商品:::::"+num);
notify();
}
public synchronized void sumer(){
if(!flag){
System.out.println("仓库里没有货,不能消费");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.flag=false;
this.num--;
System.out.println(Thread.currentThread().getName()+"消费商品::::::"+num);
notify();

}

}


第一个线程

public class Thread_1 implements Runnable{
private ResDemo resdemo;

public Thread_1(ResDemo resdemo) {
super();
this.resdemo = resdemo;
}

@Override
public void run() {
for(int i=0;i<10;i++){
this.resdemo.pro();
}

}

}


第二个线程

public class Thread_2 implements Runnable{
private ResDemo resdemo;

public Thread_2(ResDemo resdemo) {
super();
this.resdemo = resdemo;
}

@Override
public void run() {
for(int i=0;i<10;i++){
this.resdemo.sumer();
}

}

}


测试类

public class Test {
public static void main(String[] args){
ResDemo resdemo=new ResDemo(0, false);
Thread thread1=new Thread(new Thread_1(resdemo),"thread1");
Thread thread2=new Thread(new Thread_2(resdemo),"thread2");
thread2.start();
thread1.start();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: