两个线程交替相加输出

面试题:两个线程交替输出1-10

不知道wait()和notify()一定要在synchronized里,面试写的代码惨不忍睹

public class Main {
    private volatile int count = 1;
    /**
     * 输出奇数
     */
    public void print1() {
        try {
            while (count<=9) {
                synchronized (this){
                    if(count%2==0){
                        this.wait();
                    }
                    System.out.println(count++);
                    this.notify();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    /**
     * 输出偶数
     */
    public synchronized void print2() {
        try {
            while (count<=10) {
                synchronized (this){
                    if(count%2==1){
                        this.wait();
                    }
                    System.out.println(count++);
                    this.notify();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Main main = new Main();
        new Thread(main::print1).start();
        new Thread(main::print2).start();
    }
}

最初想用Atomic包,忘了包名,然后面试官让用wait和notify,结果不会

import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) {
        AtomicInteger integer=new AtomicInteger(1);
        new Thread(() -> {
            while (integer.get()<=9){
                if(integer.get()%2==1){
                    System.out.println(integer.get());
                    integer.incrementAndGet();
                }
            }
        }).start();
        new Thread(() -> {
            while (integer.get()<=10){
                if(integer.get()%2==0){
                    System.out.println(integer.get());
                    integer.incrementAndGet();
                }
            }
        }).start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值