package com.test;
class shuzi extends Thread{
public static boolean runing = false;
@Override
public void run() {
runing();//如果先运行,就让runing等于true;
for(int i = 1; i <= 26; i++){
synchronized("jo"){
System.out.print(i);
"jo".notify();
try {
if(i<26) "jo".wait();
} catch (InterruptedException e) {e.printStackTrace();}
}
}
}
public void runing(){
runing = true;
}
}
class zimu extends Thread{
@Override
public void run() {
//运行前先判断,如果runing为false,说明自己先运行了,挂起,唤醒对方
if(!shuzi.runing){
try {
synchronized("jo"){
"jo".notify();
"jo".wait();
}
} catch (InterruptedException e) {e.printStackTrace();}
}
for(char i = 'a'; i <= 'z'; i++){
synchronized("jo"){
System.out.println(i);
"jo".notify();
try {
if(i<'z') {
"jo".wait();//挂起
}
} catch (InterruptedException e) {e.printStackTrace();}
}
}
}
}
public class Test1 {
public static void main(String[] args) {
shuzi s = new shuzi();
s.start();
zimu z = new zimu();
z.start();
}
}
/**
* 我原来也不会,后来发现是可以做到的,就是逻辑判断的代码多了一点
*/
温馨提示:内容为网友见解,仅供参考