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();
}
}
}
线程通信
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.