【多线程】AB两个线程交替打印1到100

问题:使用两个线程从0到1交替打印奇数和偶数

方法一:
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static volatile boolean flag = false;
    public static AtomicInteger i=new AtomicInteger(1);
    public static void main(String[] args) throws InterruptedException {
        // 线程 A
        new Thread(()->{
            while (i.get()<=100)
            {
                if(!flag)
                {
                    System.out.println(Thread.currentThread().getName() +  " " + i.getAndIncrement());
                    flag=true;
                }
            }
        },"线程A").start();
        Thread.sleep(1000);

        // 线程 B
        new Thread(()->{
            while (i.get()<=100)
            {
                if(flag)
                {
                    System.out.println(Thread.currentThread().getName()+  " " + i.getAndIncrement());
                    flag=false;
                }
            }
        },"线程B").start();
        Thread.sleep(1000);
    }
}
方法二:
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    static AtomicInteger i=new AtomicInteger(1);
    public static void main(String[] args) throws InterruptedException {
        Object a = new Object();
        Object b = new Object();

        new Thread(new MyThread("A", b, a)).start();
        Thread.sleep(1000);
        new Thread(new MyThread("B", a, b)).start();

    }

    static class MyThread implements Runnable {
        private String name;
        private Object pre;
        private Object self;

        public MyThread(String name, Object pre, Object self) {
            this.name = name;
            this.pre = pre;
            this.self = self;
        }

        @Override
        public void run() {
            while(i.get()<=100)
            {
                synchronized (pre)
                {
                    synchronized (self)
                    {
                        System.out.println("线程"+name+":"+i.getAndIncrement());
                        self.notifyAll();
                    }
                    try {
                        if(i.get()==101)
                        {
                            pre.notifyAll();
                        }
                        else{
                            pre.wait();
                        }
                    }catch (Exception e)
                    {
                        throw new RuntimeException();
                    }
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值