前言
有很多中写法,希望可以慢慢都写出来。
1、线程共享类对象:依靠AtomicInteger是线程安全的
将 AtomicInteger currentCount 作为线程共享。
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 三个线程按次序轮流打印a,b,c AtomicInteger 实现
*
*/
public class AtomicIntegerThread implements Runnable {
private AtomicInteger currentCount = new AtomicInteger(0);
private static final Integer MAX_COUNT = 6;
private static String[] chars = {"a", "b", "c"};
private String name;
public AtomicIntegerThread(String name,AtomicInteger currentCount) {
this.name = name;
this.currentCount = currentCount;
}
@Override
public void run() {
while (currentCount.get() < MAX_COUNT) {
if (this.name.equals(chars[currentCount.get() % 3])) {
printAndPlusOne(this.name);
}
}
}
public void printAndPlusOne(String content) {
System.out.print(content);
currentCount.getAndIncrement();
}
public static void main(String[] args) {
AtomicInteger currentCount = new AtomicInteger(0);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 3, 20, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>());
threadPoolExecutor.execute(new AtomicIntegerThread("a",currentCount));
threadPoolExecutor.execute(new AtomicIn

最低0.47元/天 解锁文章
2634





