import java.util.*; import java.util.concurrent.TimeUnit;
A 线程添加10个元素,B线程监视当A线程添加了5个元素则结束
public class Test { volatile List<Object> list= new ArrayList();
public void add(Object o){
list.add(o);
}
public int size(){
return list.size();
}
public static void main(String args[]) {
Test c = new Test();
final Object lock = new Object();
new Thread(() -> {
synchronized (lock) {
if (c.size() != 5) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
System.out.println("t2 is end");
}
}, "t2").start();
new Thread(() -> {
synchronized (lock) {
for (int i = 0; i < 10; i++) {
c.add(new Object());
System.out.println("add" + i);
if (c.size() == 5) {
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "t1").start();
}
}
public class Test2 {
List<Object> list= new ArrayList();
public void add(Object o){
list.add(o);
}
public int size(){
return list.size();
}
public static void main(String[] args) {
Test2 test2 = new Test2();
CountDownLatch latch = new CountDownLatch(1);
new Thread(()->{
if(test2.size()!=5) {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t2");
new Thread(()->{
for (int i = 0; i <10 ; i++) {
test2.add(new Object());
System.out.println("add"+i);
if(test2.size()==5)
latch.countDown();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t1");
}
}
来源:oschina
链接:https://my.oschina.net/u/2511906/blog/3221723