调用LockSupport方法实现
import java.util.concurrent.locks.LockSupport;
public class Test1 {
static Thread t1 = null;
static Thread t2 = null;
public static void main(String[] args) {
Share share = new Share();
t1 = new Thread(()->{
for(int i = 0; i < 50; i++){
try {
share.add();
} catch (InterruptedException e) {
e.printStackTrace();
}
LockSupport.unpark(t2);
LockSupport.park();
}
},"t1");
t2 = new Thread(()->{
for (int i = 0; i < 50; i++) {
LockSupport.park();
try {
share.sub();
} catch (InterruptedException e) {
e.printStackTrace();
}
LockSupport.unpark(t1);
}
},"t2");
t1.start();
t2.start();
}
static class Share {
int n = 0;
synchronized void add() throws InterruptedException {
String name = Thread.currentThread().getName();
n += 1;
System.out.println(name+"线程执行完add方法: "+n);
Thread.sleep(50);
}
synchronized void sub() throws InterruptedException {
String name = Thread.currentThread().getName();
n -= 1;
System.out.println(name+"线程执行完sub方法后n的值: "+n);
Thread.sleep(50);
}
}
}
使用notify和wait实现
import java.util.concurrent.CountDownLatch;
public class CSpract {
public static CountDownLatch countDownLatch = new CountDownLatch(1);
public static void main(String[] args) {
Object lock = new Object();
Share share = new Share();
Thread t1 = new Thread(() -> {
try {
synchronized (lock) {
countDownLatch.countDown();
while (true) {
share.add();
lock.notify();
lock.wait();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}, "t1");
Thread t2 = new Thread(() -> {
try {
countDownLatch.await();
synchronized (lock) {
while (true) {
share.sub();
lock.notify();
lock.wait();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}, "t2");
t1.start();
t2.start();
}
static class Share {
int n = 0;
synchronized void add() throws InterruptedException {
String name = Thread.currentThread().getName();
n += 1;
System.out.println(name + "线程执行完add方法: " + n);
Thread.sleep(50);
}
synchronized void sub() throws InterruptedException {
String name = Thread.currentThread().getName();
n -= 1;
System.out.println(name + "线程执行完sub方法后n的值: " + n);
Thread.sleep(50);
}
}
}