package com.jack.test;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ShareData05 {
public int number = 0;
public int countA = 0;
public int countB = 0;
public Lock lock = new ReentrantLock();
private Condition cod = lock.newCondition();
public void increment() throws InterruptedException {
lock.lock();
while (number != 0) {
cod.await();
}
++number;
System.out.println(Thread.currentThread().getName() + number);
cod.signalAll();
System.out.println(Thread.currentThread().getName() + "执行了" + (++countA) + "次");
lock.unlock();
}
public void decrement() throws InterruptedException {
lock.lock();
while (number == 0) {
cod.await();
}
number--;
System.out.println(Thread.currentThread().getName() + number);
cod.signalAll();
System.out.println(Thread.currentThread().getName() + "执行了" + (++countB) + "次");
lock.unlock();
}
}
/**
*
* @author jack 题目:两个线程,轮替操作,实现一个线程对初始值为零的一个变量,实现一个线程加一, 另外一个线程减一,来10轮
*/
public class ThreadDemo05 {
public static void main(String[] args) {
ShareData05 sd = new ShareData05();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
sd.decrement();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "AA").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
sd.increment();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "BB").start();
}
}