两个线程交替打印奇数偶数的两种实现。

这是一个经典的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) {}
            }
        }
    }
}

这两种都可以实现交替打印,推荐使用第二种,因为面试官如果问到这个问题,一定是想了解你对线程间通讯了解和掌握程度,第一种虽然也是两个线程,但是都是同一种实现,不能完全展示面试者对多线程通讯的精通程度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专注网赚的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值