使用两个线程交替打印 1-10,要求一个线程打印所有偶数,另一个线程打印奇数。(例:
Thread-0:1 Thread-1:2 Thread-0:3 Thread-1:4 Thread-0:5 Thread-1:6…)
public class Test5 {
static volatile int i=1;
public static void main(String[] args) {
T1 t1=new T1();
t1.start();
T2 t2=new T2();
t2.start();
}
}
class T1 extends Thread {
@Override
public void run() {
while (Test5.i <= 10) {
if (Test5.i % 2 == 1) {
System.out.println(Thread.currentThread().getName() +
":" + Test5.i);
Test5.i++;
}
}
}
}
class T2 extends Thread{
@Override
public void run(){
while (Test5.i<=10){
if (Test5.i%2==0){
System.out.println(Thread.currentThread().getName()+":"+Test5.i);
Test5.i++;
}
}
}
}