多线程采用不同的方法操作一个资源的例子
2015-12-06 16:38
423 查看
资源类
两个不同的方法,都是同步方法,当一个线程调用一个同步方法时,另外一个线程是不能调用另一个同步方法。
要特别注意标记的操作。
notify()执行后,如果这个线程后面还是程序未执行完,要先执行完,才会让出对象的锁。
第一个线程
第二个线程
测试类
两个不同的方法,都是同步方法,当一个线程调用一个同步方法时,另外一个线程是不能调用另一个同步方法。
要特别注意标记的操作。
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(); } }
相关文章推荐
- Nginx+uWSGI+Django部署
- hdu1348 Wall (求凸包周长)
- javascript导图
- JAVA 输入输出流 IO 总结
- JavaScript之target和currentTarget
- 文本分类(一)
- 增强For循环
- 贝叶斯决策
- 第十四周实践项目三--验证是否为BST
- Javascript根据变量来动态查询数组或Json的数据
- SQL LEFT JOIN 关键字
- 数据注解特性--MaxLength&&MinLength
- 请核实文件或文件夹是否存在,而您拥有服务器的必要权限才能执行请求
- Ubuntu下出现授权问题
- uva 624 CD (01背包)
- hdoj 5533 Dancing Stars on Me
- Segmentation fault (core dumped)
- PHP的SESSION机制
- mysql存储过程、触发器、事物高级应用
- 信息安全系统设计基础第十三周学习总结