本帖最后由 丸子 于 2014-8-28 11:02 编辑
public class ThreadExample {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final Service1 s=new Service1();
Thread t1=new Thread(){
public void run(){
for(int i=0;i<7;i++){
s.print1();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t2=new Thread(){
public void run(){
for(int i=0;i<7;i++){
s.print2();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
t1.start();
t2.start();
}
}
class Service1 {
int ss=0;
public void print1(){
if(ss!=0)
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(this){
for(int i=0;i<3;i++)
System.out.println(Thread.currentThread().getName()+"A");
System.out.println();
}
ss=1;
this.notify();
}
public void print2(){
if(ss!=1)
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(this){
for(int i=0;i<3;i++)
System.out.println(Thread.currentThread().getName()+"B");
System.out.println();
}
ss=0;
this.notify();
}
}
|
|