1、自定义容器提供新增元素(add)和获取元素(get)的方法
2、启动两个线程,线程一向容器中新增10个元素,线程二监听容器元素数量,当容器元素数量为5时,线程二输出信息并停止
实现方式一:
public class Test_13 {
volatile List<Object> list=new ArrayList<Object>();
public void add(Object o){
list.add(o);
}
public int get(){
return list.size();
}
public static void main(String[] args){
final Test_13 t=new Test_13();
final Object o=new Object();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (o){
System.out.println(Thread.currentThread().getName()+"is Start 【1】");
for(int i=0;i<10;i++){
t.add(new Object());
System.out.println("add : " + i);
if(t.get()==5){
o.notifyAll(); //唤醒线程二
try {
o.wait(); //线程一进入等待队列
}catch (InterruptedException e){
e.printStackTrace();
}
}
try {
TimeUnit.SECONDS.sleep(1);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (o){
System.out.println(Thread.currentThread().getName()+" is Start 【2】");
if(t.get()!=5){
try{
o.wait(); //线程二进入等待队列
}catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" is stop");
o.notifyAll(); //唤醒线程一
}
}
}).start();
}
}
实现方式二:
public class Test_13 {
volatile List<Object> list=new ArrayList<Object>();
public void add(Object o){
list.add(o);
}
public int get(){
return list.size();
}
public static void main(String[] args){
final Test_13 t=new Test_13();
CountDownLatch count=new CountDownLatch(1);
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"is Start 【1】");
for(int i=0;i<10;i++){
t.add(new Object());
System.out.println("add : " + i);
if(t.get()==5){
count.countDown();//唤醒线程二
}
try {
TimeUnit.SECONDS.sleep(1);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" is Start 【2】");
if(t.get()!=5){
try{
count.await(); //线程二进入等待队列
}catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" is stop");
}
}).start();
}
}