多线程循环打印奇数和偶数

多线程循环打印奇数和偶数

面试阿里遇到的题目

面试阿里,需要在线做题。第一题就是循环打印的题目。具体题目为两个线程,一个打印奇数,一个打印偶数。

思路

直观的思路是,用reentrantLock,然后还有Condition来实现线程的协作。但是面试官也问到有没有无锁算法。这里既然是无锁算法,那肯定要采用cas这些了,因此直接用atomic类来实现就好了。

具体代码

public class Interview {
	static volatile AtomicInteger count = new AtomicInteger(0);
	static class T1 implements Runnable {
	    @SneakyThrows
	    @Override
	    public void run() {
	        System.out.println("T1 start run");
	        while (count.get() <= 100) {
	            if (count.get()%2 != 0) {
	                System.out.println("T1:" + count.get());
	                count.incrementAndGet();
	            }
	            else {
	                continue;
	            }
	        }
	    }
	}
	static class T2 implements Runnable {
	    @SneakyThrows
	    @Override
	    public void run() {
	
	        System.out.println("T2 start run");
	
	        while (count.get() <= 100) {
	            if (count.get()%2 == 0) {
	                System.out.println("T2:" + count.get());
	                count.incrementAndGet();
	            }
	            else {
	                continue;
	            }
	        }
	    }
	}
}

这里其实就直接采用

好的,这是一个简单的Java程序,用于创建两个线程分别输奇数偶数,每个线程循环10次: ```java public class PrintNumbers { public static void main(String[] args) { Thread oddThread = new Thread(new PrintOdd()); Thread evenThread = new Thread(new PrintEven()); oddThread.start(); evenThread.start(); try { oddThread.join(); evenThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } static class PrintOdd implements Runnable { @Override public void run() { for (int i = 1; i <= 20; i += 2) { System.out.println(Thread.currentThread().getName() + ": " + i); } } } static class PrintEven implements Runnable { @Override public void run() { for (int i = 2; i <= 20; i += 2) { System.out.println(Thread.currentThread().getName() + ": " + i); } } } } ``` 在这个程序中,我们定义了两个内部类 `PrintOdd` `PrintEven`,分别用于输奇数偶数。在每个类中,我们使用了 `for` 循环来生成一系列奇数偶数,并使用 `System.out.println` 方法输它们。注意,我们在输中加入了当前线程的名称,以便区分两个线程的输。 然后,在主函数中,我们创建了两个线程 `oddThread` `evenThread`,分别用于执行 `PrintOdd` `PrintEven` 类。我们使用 `start` 方法启动这两个线程,并使用 `join` 方法等待它们的完成。注意,我们需要等待两个线程完成后才能退程序,否则可能会现输的混乱。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值