package com.example.csv;
import java.util.ArrayList;
import java.util.List;
public class Test {
volatile List<Integer> list =new ArrayList<>();
public void add(int i){
list.add(i);
}
public int size(){
return list.size();
}
/* public static void main(String[] args) {
Test test=new Test();
CountDownLatch countDownLatch=new CountDownLatch(1);
new Thread(()->{
try {
*//*if (test.size()!=5){*//*
countDownLatch.await();
*//* }*//*
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("結束:"+test.size());
}).start();
new Thread(()->{
try {
for (int i = 0; i < 10; i++) {
if (test.size() == 5) {
countDownLatch.countDown();
}
test.add(i);
System.out.println(i);
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}*/
public static void main(String[] args) {
Test test=new Test();
Object obj=new Object();
new Thread(()->{
synchronized (obj){
try{
for (int i = 0; i < 10; i++) {
test.add(i);
System.out.println(i);
if (test.size()== 5) {
//监控到集合长度等于5时,唤醒沉睡的线程
obj.notify();
//使当前线程阻塞
obj.wait();
}
}
//obj.notify();
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
new Thread(()->{
synchronized (obj){
try{
if (test.size() != 5) {
//使当前线程阻塞
obj.wait();
}
//监控到集合长度等于5时,do something
System.out.println("监控到集合长度等于5时,do something");
obj.notify();
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}
}