【java】两个线程交替输出1-100
package test;
/**
* 两个线程交替输出1-100
*/
public class ThreadTest {
static int lock = 0;
static int show = 1;
public static void main(String[] args) {
Thread thread1 = new Thread(){
private String name="Tread1";
@Override
public void run() {
super.run();
while(true){
if(lock==0){
lock = 1;
// System.out.println(name+"获取到锁");
if(show%2==1){
System.out.println(name+":"+show);
show++;
}
lock = 0;
// System.out.println(name+"释放锁");
}
if(show>=100){
break;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
}
};
Thread thread2 = new Thread(){
private String name="Tread2";
@Override
public void run() {
super.run();
while(true){
if(lock==0){
lock = 1;
// System.out.println(name+"获取到锁");
if(show%2==0){
System.out.println(name+":"+show);
show++;
}
lock = 0;
// System.out.println(name+"释放锁");
}
if(show>=100){
break;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
}
};
thread1.start();
thread2.start();
}
}