【代码】
package com.alipay.insttrade.common.service.integration.payment;
public class Test{
public static int count = 1;
public static final Object lock = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
while(count<=100){
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + "抢到锁");
//算是一种double check
if (count <= 100 && count%2==1) {
System.out.println(Thread.currentThread().getName() + ":" + count);
count++;
}
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
while(count<=100){
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + "抢到锁");
if (count <= 100 && count%2==0) {
System.out.println(Thread.currentThread().getName() + ":" + count);
count++;
}
}
}
}
});
thread1.start();
thread2.start();
}
}
【output】
【缺点】
可以看到虽然实现了题目。
但实际上并不代表着这两个线程在交替运行,因为线程是随机抢锁的,有可能连续十次都是偶数线程好运抢到了锁,只是因为不满足条件,抢到锁后发现不符合奇偶啥也不干,浪费资源
1.2 实现方式2-----线程间通信之wait/notify
package com.alipay.insttrade.common.service.integration.payment;
public class Test{
public static void main(String[] args) throws InterruptedException {
new Thread(new TurningRunner(), "奇数").start();
// 短暂休眠,确保线程执行顺序
Thread.sleep(50);
new Thread(new TurningRunner(), "偶数").start();
}
static class TurningRunner implements Runnable {
private static int count = 1;
private static final Object lock = new Object();
@Override
public void run() {
while (count <= 100) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + ":" + count);
count ++;
//注意notify和wait顺序不能错
lock.notify(); // 唤醒另一个线程
if (count < 100) {
try {
lock.wait(); // 释放锁,进入阻塞状态,等待被唤醒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}



