这是一个经典的java多线程面试题,今天分享一下实现交替打印的两种实现方式。
第一种:
public class ThreadTest {
public static void main(String[] args) {
PrintNum p=new PrintNum();
Thread t1=new Thread(p);
Thread t2=new Thread(p);
t1.setName("甲");
t2.setName("乙");
t1.start();
t2.start();
}
}
class PrintNum implements Runnable{
int num=1;
@Override
public void run() {
synchronized (this) {
while(true){
notify();//唤醒wait()的一个或者所有线程
if (num <= 100) {
System.out.println(Thread.currentThread().getName() + ":" + num);
num++;
} else {
break;
}
try {
wait();//释放当前的锁,另一个线程就会进来
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
第二种:
public class ThreadTest3 {
public static void main(String[] args) {
Counter counter = new Counter();
new Thread(new PrintOdd(counter)).start();
new Thread(new PrintEven(counter)).start();
}
}
class Counter {
public int value = 1;
public boolean odd = true;
}
class PrintOdd implements Runnable {
public Counter counter;
public PrintOdd(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
while (counter.value <= 100) {
synchronized(counter) {
if (counter.odd) {
System.out.println(counter.value);
counter.value++;
counter.odd = !counter.odd;
//很重要,要去唤醒打印偶数的线程
counter.notify();
}
try {
counter.wait();
} catch (InterruptedException e) {}
}
}
}
}
class PrintEven implements Runnable {
public Counter counter;
public PrintEven(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
while (counter.value <= 100) {
synchronized (counter) {
if (!counter.odd) {
System.out.println(counter.value);
counter.value++;
counter.odd = !counter.odd;
counter.notify();
}
try {
counter.wait();
} catch (InterruptedException e) {}
}
}
}
}
这两种都可以实现交替打印,推荐使用第二种,因为面试官如果问到这个问题,一定是想了解你对线程间通讯了解和掌握程度,第一种虽然也是两个线程,但是都是同一种实现,不能完全展示面试者对多线程通讯的精通程度。