package qzu.guitai;
/**
* 本程序實現子線程執行10次,然後到主線程執行100次,子線程和主線程每個執行五十次。
* @author Administrator
*
*/
public class TraditionalThreadSynchronized {
public static void main(String[] args) {
new TraditionalThreadSynchronized().init();
}
/**
* 該方法創建一個子線程,子線程中循環執行五十次調用sub方法和循環五十次調用main方法
*/
public void init(){
final Business business=new Business();
new Thread(){
public void run(){
for (int i = 0; i < 50; i++) {
business.sub();
}
}
}.start();
for (int i = 0; i < 50; i++) {
business.main();
}
}
/**
* 該類的sub方法實現打印10次,main方法打印100次,兩個方法都採用了同步鎖來實現信息通信
* @author 黃賢亨
*
*/
class Business{
private boolean flag=true;
public synchronized void sub(){
if(flag)
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int j = 0; j < 10; j++) {
System.out.println(Thread.currentThread().getName()
+ "==" +j);
}
flag=true;
this.notify();
}
public synchronized void main(){
if(!flag)
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int j = 0; j < 100; j++) {
System.out.println(Thread.currentThread().getName()
+ "-----" + j);
}
flag=false;
this.notify();
}
}
}
線程通信
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.