双线程交替打印0-100的三种方法

方法一:传统wait/notifyAll+等待标记mark

static AtomicInteger i = new AtomicInteger(1);
static Object lock = new Object();
static int mark = 1;
Thread a = new Thread(() -> {
    while (i.get() < 100){
        synchronized (lock){
            while (mark != 1){
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("线程a:" + i.getAndIncrement());
            lock.notifyAll();
            mark = 2;
        }
    }
});
Thread b = new Thread(() -> {
    while (i.get() <= 100){
        synchronized (lock){
            while (mark != 2){
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("线程b:"+i.getAndIncrement());
            lock.notifyAll();
            mark = 1;
        }
    }
});
a.start();
b.start();

方法二:信号量Semaphore

static AtomicInteger i = new AtomicInteger(1);
static Semaphore s1 = new Semaphore(1);
static Semaphore s2 = new Semaphore(0);
Thread a = new Thread(() -> {
    try {
        while(i.get() < 100){
            s1.acquire();
            System.out.println("线程-a:" + i.getAndIncrement());
            s2.release();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});

Thread b = new Thread(() -> {
    try {
        while(i.get() < 100){
            s2.acquire();
            System.out.println("线程-b:" + i.getAndIncrement());
            s1.release();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});
a.start();
b.start();

方法三:LockSupport

static AtomicInteger i = new AtomicInteger(1);
Thread [] threads = new Thread[2];
threads[0] = new Thread(() -> {
    while (i.get() < 100){
        System.out.println("线程a:" + i.getAndIncrement());
        LockSupport.unpark(threads[1]);
        LockSupport.park();
    }
});

threads[1] = new Thread(() -> {
    while (i.get() < 100){
        LockSupport.park();
        System.out.println("线程b:" + i.getAndIncrement());
        LockSupport.unpark(threads[0]);
    }
});
threads[0].start();
threads[1].start();

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值