两个线程依次打印1、2、3…等有序的数字
创建自定义类及定义属性
public class Num{
public int i = 1;
public boolean flag = false;
}
创建线程打印输出
public class Test(){
public static void main(String[] args) throws Exception {
int count = 101;
Num num = new Num();
Thread t1 = new Thread(()->{
try {
while(num.i < count){
synchronized(num){
if(num.flag){
num.wait();
}else{
System.out.println(Thread.currentThread().getName() + "___" + num.i);
num.i++;
num.flag = true;
num.notify();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(()->{
try{
while(num.i < count){
synchronized(num){
if(!num.flag){
num.wait();
}else{
System.out.println(Thread.currentThread().getName() + "___" + num.i);
num.i++;
num.flag = false;
num.notify();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
});
t1.setName("thread_1");
t2.setName("thread_2");
t1.start();
t2.start();
}
}
输出结果
