import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class StrangePrinter {
private int max;
private AtomicInteger status = new AtomicInteger(1); // AtomicInteger保证可见性,也可以用volatile
public StrangePrinter(int max) {
this.max = max;
}
public static void main(String[] args) {
StrangePrinter strangePrinter = new StrangePrinter(100);
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(strangePrinter.new MyPrinter("Print1", 0));
executorService.submit(strangePrinter.new MyPrinter("Print2", 1));
executorService.shutdown ();
}
class MyPrinter the implements the Runnable {
Private String name;
Private int type; // print type, 0: the representative print odd, 1: Representative print the even
public MyPrinter (String name, int type) {
this.name name =;
this.type = type;
}
@Override
public void RUN () {
IF (type ==. 1) {
the while (status.get () <= max) {
the synchronized (StrangePrinter.class) {// lock, the following operation is to ensure an atomic operation
// print even
if (status.get () <= max && status.get ()% 2 == 0) {// print even
System.out.println(name + " - " + status.getAndIncrement());
}
}
}
} else {
while (status.get() <= max) {
synchronized (StrangePrinter.class) { // 加锁
// 打印奇数
if (status.get() <= max && status.get() % 2 != 0) { // 打印奇数
System.out.println(name + " - " + status.getAndIncrement());
}
}
}
}
}
}
}
java thread pool to achieve print base, the even
Guess you like
Origin www.cnblogs.com/tangsonghuai/p/10942281.html
Recommended
Ranking