一、sync的wait和notify
public class T04 {
private static List lists = new ArrayList();
private static void add(Object o) {
lists.add(o);
}
private static int size() {
return lists.size();
}
public static void main(String[] args) {
Object lock = new Object();
new Thread(() -> {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t2 结束");
lock.notify();
}
}, "t2").start();
new Thread(() -> {
synchronized (lock) {
for (int i = 0; i < 10; i++) {
add(new Object());
System.out.println("add: " + i);
if (size() == 5) {
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}, "t1").start();
}
}
二、CountDownLatch
public class T05 {
private static List lists = new ArrayList();
private static void add(Object o) {
lists.add(o);
}
private static int size() {
return lists.size();
}
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(1);
CountDownLatch latch2 = new CountDownLatch(1);
new Thread(()->{
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t2 结束");
latch2.countDown();
}, "t2").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
add(new Object());
System.out.println("add: " + i);
if (size() == 5) {
latch.countDown();
try {
latch2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "t1").start();
}
}
三、LockSupport
public class T06 {
private static List lists = new ArrayList();
private static void add(Object o) {
lists.add(o);
}
private static int size() {
return lists.size();
}
private static Thread t1 = null, t2 = null;
public static void main(String[] args) {
t2 = new Thread(() -> {
LockSupport.park();
System.out.println("t2 结束");
LockSupport.unpark(t1);
}, "t2");
t1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
add(new Object());
System.out.println("add: " + i);
if (size() == 5) {
LockSupport.unpark(t2);
LockSupport.park();
}
}
}, "t1");
t2.start();
t1.start();
}
}