两个线程分别打印|两个线程分别打印 1- 100,A 打印偶数, B打印奇数。
1. 直接用CAS中的AtomicInteger
package concurency.chapter13;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @auther draymonder
*/
public class PrintOddAndEven {
public static volatile boolean flag = false;
public static AtomicInteger num = new AtomicInteger();
public static void main(String[] args) {
new Thread(()->{
while(num.get() < 100) {
if(flag) {
System.out.println(Thread.currentThread() +" " + num.getAndIncrement());
flag = false;
}
}}, "奇数").start();
new Thread(()->{
while(num.get() < 100) {
if(!flag) {
System.out.println(Thread.currentThread() + " " + num.getAndIncrement());
flag = true;
}
}
}, "偶数").start();
}
}
第二种 带锁版 注意 奇数是 < 100 偶数是<=100
package concurency.chapter13;
/**
* @auther draymonder
*/
public class Print2 {
// flag = 0 now oddflag = 1 now even
public static volatile boolean flag = true;
public static final Object lock = new Object();
public static volatile int num = 0;
public static void main(String[] args) {
new Thread(()->{
while(num < 100) {
synchronized (lock) {
if (flag) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread() + " " + num++);
flag = true;
lock.notifyAll();
}
}
},"奇数").start();
new Thread(()->{
while(num <= 100) {
synchronized (lock) {
if (!flag) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread() + " " + num++);
flag = false;
lock.notifyAll();
}
}
},"偶数").start();
}
}
【两个线程分别打印|两个线程分别打印 1- 100,A 打印偶数, B打印奇数。】转载于:https://www.cnblogs.com/Draymonder/p/10562488.html
推荐阅读
- Linux下面如何查看tomcat已经使用多少线程
- 刘婵为何不娶关羽的女儿为妻子,而为何要娶张飞的两个女儿
- 多线程NSOperation
- 说睡
- 有人与我谈格局
- ||11|2019年9月9日
- 活的教导7:两个阶段
- 两个人在一起,最怕将就。
- spring|spring boot中设置异步请求默认使用的线程池
- 两个心得