两个线程互相通信,交换着运行,下面的代码,可以打印出以上的效果,
public class ThreadCommunication {
/**
* @param args
*/
public static void main(String[] args) {
final printChar business = new printChar();
new Thread(
new Runnable() {
@Override
public void run() {
for(int i=1;i<=20;i++){
business.sub1(i);
}
}
}
).start();
for(int i=1;i<=20;i++){
business.sub2(i);
}
}
}
class printChar {
private boolean bShouldSub1 = true;
public synchronized void sub1(int i){
while(!bShouldSub1){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=2;j++){
System.out.print("a");
}
bShouldSub1 = false;
this.notify();
}
public synchronized void sub2(int i){
while(bShouldSub1){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print("b");
bShouldSub1 = true;
this.notify();
}
}
|