线程题:交替打印1-100
这里演示两个线程,一个打印奇数,一个打印偶数
方式一:synchronized + FixedThreadPool
public class example {
private static int count = 1;
private static final Object lock = new Object();
public static void main(String[] args) {
ThreadFactory factory = new ThreadFactory() {
AtomicInteger ai = new AtomicInteger(1);
@Override
public Thread newThread(@NotNull Runnable r) {
Thread thread = new Thread(r, ai.getAndIncrement() + ": ");
return thread;
}
};
ExecutorService executorService = Executors.newFixedThreadPool(2, factory);
executorService.submit(example::printOdd);
executorService.submit(example::printEven);
}
private static void printOdd() {
while (count <= 100) {
synchronized (lock) {
if(count % 2 != 0 && count <= 100) {
System.out.println(Thread.currentThread().getName() + ": " + count);
count++;
}
}
}
}
private static void printEven() {
while (count <= 100) {
synchronized (lock) {
if(count % 2 == 0 && count <= 100) {
System.out.println(Thread.currentThread().getName() + ": " + count);
count++;
}
}
}
}
}
方法二:ReentrantLock + Condition
public class example2 {
static ReentrantLock lock = new ReentrantLock();
static int count = 1;
public static void main(String[] args) {
// 两个 condition
Condition odd = lock.newCondition();
Condition even = lock.newCondition();
new Thread(() -> {
while(count <= 100) {
lock.lock();
try {
try {
if (count % 2 != 0) {
System.out.println(Thread.currentThread().getName() + ": " + count);
count++;
}
even.signal();
odd.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}finally {
lock.unlock();
}
}
}, "odd").start();
new Thread(() -> {
while(count <= 100) {
lock.lock();
try {
try {
if (count % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ": " + count);
count++;
}
odd.signal();
even.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}finally {
lock.unlock();
}
}
}, "even").start();
}
}