方式一:Lock+Condition+while
public class Test {
public static void main(String[] args) {
Data data = new Data();
new Thread(() -> {
for (int i = 0; i <= 5; i++) {
data.printOs();
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 5; i++) {
data.printJs();
}
}, "B").start();
}
static class Data{
// 使用公平锁
private final ReentrantLock lock = new ReentrantLock(true);
// lock 监视器
private final Condition condition = lock.newCondition();
// 需要打印的数
private int number = 0;
// 打印偶数
public void printOs(){
lock.lock();
try {
while (number % 2 != 0){
condition.await();
}
System.out.println("[" + Thread.currentThread().getName() + "] " + number);
number++;
condition.signalAll();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
// 打印奇数
public void printJs(){
lock.lock();
try {
while (number % 2 == 0){
condition.await();
}
System.out.println("[" + Thread.currentThread().getName() + "] " + number);
number++;
condition.signalAll();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
}
方式二:synchronized+while
public class Test3 {
public static void main(String[] args) {
Data data = new Data();
new Thread(()->{
try {
for (int i = 0; i <= 5; i++) {
data.printOs();
}
}catch (Exception e){
e.printStackTrace();
}
},"A").start();
new Thread(()->{
try {
for (int i = 0; i < 5; i++) {
data.printJs();
}
}catch (Exception e){
e.printStackTrace();
}
},"B").start();
}
static class Data{
private int number = 0;
public synchronized void printOs() throws InterruptedException {
while (number % 2 != 0){
this.wait();
}
System.out.println("[" + Thread.currentThread().getName() + "] " + number);
number++;
this.notifyAll();
}
public synchronized void printJs() throws InterruptedException {
while (number % 2 == 0){
this.wait();
}
System.out.println("[" + Thread.currentThread().getName() + "] " + number);
number++;
this.notifyAll();
}
}
}
方式三:CountDownLatch+while
public class Test2 {
private static AtomicInteger num = new AtomicInteger(0);
private static CountDownLatch countDownLatch = new CountDownLatch(2);
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread() {
@Override
public void run() {
while (num.intValue() < 10) {
if (num.intValue() % 2 == 1) {
System.out.println("A:"+num.intValue());
num.incrementAndGet();
}
countDownLatch.countDown();
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
while (num.intValue() <= 10) {
if (num.intValue() % 2 == 0) {
System.out.println("B:"+num.intValue());
num.incrementAndGet();
}
countDownLatch.countDown();
}
}
};
t1.start();
t2.start();
countDownLatch.await();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/69722.html