package com.thread_test;
/**
* Created by zhen on 2017-05-27.
* 经验:要用到共同数据(包括同步锁)的若干个方法应该归在同一个类身上,这种设计正好体现了高内聚和程序的健壮性。
* 需求:
* 子线程输出10次,主线程输出100次,再子线程输出10次,主线程输出100次,循环50次
* 思路:
* 1、先实现子线程输出10次,主线程输出100次,50次
* 2、将业务代码提取,注意:那个循环50次不属于业务代码,输出控制代码
* 3、保证代码在执行一次的过程中不被侵入,使用同步,并且同一把锁
* 4、现在可以确保的是主线程和子线程在一次业务执行过程中时不受干扰的,如何让他们有序运行呢?加入一个中间变量,在业务中依据中间变量判断是否自己执行
* 5、注意,判断中间变量是否正确使用的是while而不是if,为了保证程序的健壮性,应为有可能唤醒是意外的属性而不是正常情况
* 对于某一个参数的版本,实现中断和虚假唤醒是可能的,而且此方法应始终在循环中使用:
synchronized (obj) {
while (<condition does not hold>)
obj.wait();
... // Perform action appropriate to condition
}
*/
public class TraditionalThreadCommunication {
public static void main(String[] args){
final Business business = new Business();
new Thread(new Runnable(){
@Override
public void run() {
for(int i = 1; i <= 50; i++){
business.sub(i);
}
}
}).start();
for(int i = 1; i <= 50; i++){
business.main(i);
}
}
}
class Business{
private static boolean isSubRun = true;
public synchronized void main(int i){
while(!isSubRun){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("main thread run time is " + i);
for(int j = 1; j <= 100; j++){
System.out.println("main thread out " + j);
}
isSubRun = false;
this.notify();
}
public synchronized void sub(int i){
while(isSubRun){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("sub thread run time is " + i);
for(int j = 1; j <= 10; j++){
System.out.println("sub thread out " + j);
}
isSubRun = true;
this.notify();
}
}