线程的互斥与同步通信 - 例子:子主线程打印,子主线程互补干扰问题
2015-12-30 14:35
302 查看
一. 互斥
结局java线程中的互斥问题的的方法
1.同步代码块,将敏感数据或者敏感操作放在同步代码块里,args代表一个参照,注意:多个方法调用同步代码块需要保证参照相同
※ args:可以是对象,可以是属性,也可以是类的字节码(类的字节码Object.class,jvm中唯一)
2.synchronized作为方法的修饰符
二. 同步通信
同步通信使用Object提供的三个方法wait ,notify和notfiyAll三个方法,简单的理解为线程之间的通信,一个线程通知另一个线程
三. JAVA一个经典习题
子线程循环10次,紧接着主线程循环100次,紧接着子线程循环10次,主线程100次,如此往复50次
实现原理:利用线程之间的通信获取flag的值,来确定是不是应该执行或者是应该停止
注意这里的判断使用的是while而不是if,使用while的好处是可以自检
结局java线程中的互斥问题的的方法
1.同步代码块,将敏感数据或者敏感操作放在同步代码块里,args代表一个参照,注意:多个方法调用同步代码块需要保证参照相同
synchronized (args) { // Code }
※ args:可以是对象,可以是属性,也可以是类的字节码(类的字节码Object.class,jvm中唯一)
2.synchronized作为方法的修饰符
public synchronized void sync(int i){ System.out.println(" message "); }
二. 同步通信
同步通信使用Object提供的三个方法wait ,notify和notfiyAll三个方法,简单的理解为线程之间的通信,一个线程通知另一个线程
三. JAVA一个经典习题
子线程循环10次,紧接着主线程循环100次,紧接着子线程循环10次,主线程100次,如此往复50次
public class TraditionalThreadTest { public static void main(String[] args) { //主线程 final BusinessTest b = new BusinessTest(); new Thread(new Runnable() { //子线程 @Override public void run() { for (int i = 1; i <= 50; i++) { b.sub(i); } } }).start(); for (int i = 1; i <= 50; i++) { b.main(i); } } } class BusinessTest{ private boolean flag = true; public synchronized void sub(int i){ while (!flag) { //true 執行 try { this.wait(); //false是等待 } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 10; j++) { System.out.println("子线程 : "+ j + ",第"+ i +"次打印"); } flag = false; this.notify(); //通知下一个线程 System.out.println(); } public synchronized void main(int i){ while (flag) { //false 執行 try { this.wait(); //true 等待 } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 10; j++) { System.out.println("主线程 : "+ j + ",第"+ i +"次打印"); } flag = true; this.notify(); //通知下一个线程 System.out.println(); } }
实现原理:利用线程之间的通信获取flag的值,来确定是不是应该执行或者是应该停止
注意这里的判断使用的是while而不是if,使用while的好处是可以自检
相关文章推荐
- git fork
- 最近做个东西 写了一个HTML解析程序
- 如何部署tomcat项目到远程服务器上
- 模二加计算
- Android实现圆角Button按钮
- 世界是数字的(三)
- iOS Crash文件的解析(一)
- CentOS系统启动流程
- Java与C/C++有什么区别
- Linux(CentOS)常用命令
- github学习
- 在Laravel中一步一步创建Packages
- Java与C/C++有什么区别
- 新公司任职前
- Git 使用vi或vim命令打开、关闭、保存文件
- 完成端口(CompletionPort)详解 - 手把手教你玩转网络编程系列之三
- sed命令详解
- 初步使用HttpURLConnection
- Libgdx学习笔记:封装贝塞尔曲线动作
- 面试题33:数组中出现次数超过一半的数字