内容简介:thread1-set-name-0thread1-set-name-1thread1-set-name-0
- Wait、Notify一定要在synchronized里面进行使用。
- Wait必须暂定当前正在执行的线程,并释放资源锁,让其他线程可以有机会运行
- notify/notifyall: 唤醒线程
- 共享变量
public class ShareEntity { private String name; // 线程通讯标识 private Boolean flag = false; public ShareEntity() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getFlag() { return flag; } public void setFlag(Boolean flag) { this.flag = flag; } }
- 线程1
public class CommunicationThread1 extends Thread{ private ShareEntity shareEntity; public CommunicationThread1(ShareEntity shareEntity) { this.shareEntity = shareEntity; } @Override public void run() { int num = 0; while (true) { synchronized (shareEntity) { if (shareEntity.getFlag()) { try { shareEntity.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } if (num % 2 == 0) shareEntity.setName("thread1-set-name-0"); else shareEntity.setName("thread1-set-name-1"); num++; shareEntity.setFlag(true); shareEntity.notify(); } } } }
- 线程2
public class CommunicationThread2 extends Thread{ private ShareEntity shareEntity; public CommunicationThread2(ShareEntity shareEntity) { this.shareEntity = shareEntity; } @Override public void run() { while (true) { synchronized (shareEntity) { if (!shareEntity.getFlag()) { try { shareEntity.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(shareEntity.getName()); shareEntity.setFlag(false); shareEntity.notify(); } } } }
- 请求
@RequestMapping("test-communication") public void testCommunication() { ShareEntity shareEntity = new ShareEntity(); CommunicationThread1 thread1 = new CommunicationThread1(shareEntity); CommunicationThread2 thread2 = new CommunicationThread2(shareEntity); thread1.start(); thread2.start(); }
- 结果
thread1-set-name-0
thread1-set-name-1
thread1-set-name-0
thread1-set-name-1
thread1-set-name-0
thread1-set-name-1
thread1-set-name-0
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- java中线程安全,线程死锁,线程通信快速入门
- ObjC 多线程简析(一)-多线程简述和线程锁的基本应用
- Java多线程之线程中止
- Android 的线程和线程池
- iOS 多线程之线程安全
- java多线程 线程安全问题
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Ruby on Rails实践之路
沃哈 / 科学 / 2010-5 / 48.00元
《Ruby on Rails实践之路:写给PHP和Java开发者的书》内容简介:Ruby on Rails是基于MVC模式的Web框架,用于开发基于数据库的Web应用。Ruby on Rails中内含了所需的Web服务器WEBrick。该框架配置的数据库除了缺省的MySQL外,还可以是Oracle、SQL Server等其他数据库。《Ruby on Rails实践之路:写给PHP和Java开发者的......一起来看看 《Ruby on Rails实践之路》 这本书的介绍吧!