public class Abc {
int flag=1;//开关 为1时A执行,2时B执行,3时C执行
public synchronized void Aa(){
if(flag==1){
System.out.print("我");
flag=2;
this.notify();
}else{
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public synchronized void Bb(){
if(flag==2){
System.out.print("爱");
flag=3;
this.notify();
}else{
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public synchronized void Cc(){
if(flag==3){
System.out.print("你");
flag=1;
this.notify();
}else{
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Test {
public static void main(String[] args) {
final Abc fs=new Abc();
new Thread(new Runnable() {
public void run() {
for(int i=0;i<10;i++){
fs.Aa();
fs.Bb();
fs.Cc();
System.out.println();
}
}
}).start();
}
}
方法二:
public class DoSome implements Runnable{
//三个变量 三条线程之间切换执行 一把锁是不够的 2把锁把锁 对象有锁的定义 Object对象
private String word;//线程要打印的字
private Object prev;//当前线程的上一个线程要持有的锁
private Object current;//当前线程所要持有的锁
public void run() {
for(int i=0;i<10;i++){
synchronized (prev){
synchronized (current){
System.out.print(word);
current.notify();
}
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public DoSome(String word, Object prev, Object current) {
this.word = word;
this.prev = prev;
this.current = current;
}
//打印字的操作
}
public class Test {
//
public static void main(String[] args) throws InterruptedException {
Object a =new Object();
Object b=new Object();
Object c=new Object();
Thread t1=new Thread(new DoSome("我",c,a));
Thread t2=new Thread(new DoSome("爱",a,b));
Thread t3=new Thread(new DoSome("你",b,c));
t1.start();
Thread.sleep(1000);
t2.start();
Thread.sleep(1000);
t3.start();
}
}