public class Test1 {
private A a;
private B b;
private R r;
public static void main(String[] args){
Test1 t = new Test1();
t.show();
}
public void show(){
r=new R();
a = new A(r);
b = new B(r);
a.start();
b.start();
}
}
class R{
int i=1;
boolean flag=true;
R(){}
}
class A extends Thread{
private R r;
A(R r){
this.r=r;
}
@Override
public void run() {
while(r.i<100) {
if(r.flag){
synchronized(r){
System.out.println("A="+r.i++);
r.flag=false;
}
}
}
}
}
class B extends Thread{
private R r;
B(R r){
this.r=r;
}
@Override
public void run() {
while(r.i<100) {
if(!r.flag){
synchronized(r){
System.out.println("B="+r.i++);
r.flag=true;
}
}
}
}
}
只要让两个线程控制同一份元素,定义一个boolean变量来改变线程的执行权 |