1.直接使用AtomicInteger
AtomicInteger i = new AtomicInteger();
new Thread(() -> {
while (true) {
try {
if (i.get() % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ":" + i.getAndIncrement());
}
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
while (true) {
try {
if (i.get() % 2 == 1) {
System.out.println(Thread.currentThread().getName() + ":" + i.getAndIncrement());
}
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}```
2.使用ReentrantLock的Condition
```java
final int[] i = {0};
ReentrantLock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
new Thread(() -> {
lock.lock();
try {
while (true) {
try {
if (i[0] % 2 == 0) {
condition1.await();
}
System.out.println(Thread.currentThread().getName() + ":" + i[0]++);
condition2.signal();
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}).start();
new Thread(() -> {
lock.lock();
try {
while (true) {
try {
if (i[0] % 2 == 1) {
condition2.await();
}
System.out.println(Thread.currentThread().getName() + ":" + i[0]++);
condition1.signal();
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}).start();
3.使用Semaphore
final int[] i = {0};
Semaphore semaphore1 = new Semaphore(1);
Semaphore semaphore2 = new Semaphore(0);
new Thread(() -> {
while (true) {
try {
semaphore1.acquire();
System.out.println(Thread.currentThread().getName() + ":" + i[0]++);
semaphore2.release();
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
while (true) {
try {
semaphore2.acquire();
System.out.println(Thread.currentThread().getName() + ":" + i[0]++);
semaphore1.release();
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();