当数据达到2000或者等待5秒后再次运行

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

class MyObject implements Runnable {
	private Object lock;//线程锁
	
	private List<Map<String,Object>> codes = new ArrayList<Map<String,Object>>();
	
	public MyObject() {
		this.lock = new Object();
	}
	
	public void setCodes(List<Map<String,Object>> list){
		codes.addAll(list);
		System.out.println("codes size="+codes.size());
		if(codes.size()>=2000){
			synchronized (lock) {
				System.out.println("i'm going.");
				codes.removeAll(codes);
				lock.notify();
			}
		}
	}

	
	public void run() {
		try {
			while(1==1){
				synchronized (lock) {
					lock.wait(5000L);
					System.out.println("has going");
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

public class Wait {
	public static void main(String[] args) {
		MyObject o = new MyObject();
		new Thread(o).start();
		int i=0;
		while(1==1){
			List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("123", "123");
			list.add(map);
			o.setCodes(list);
			i++;
			if(i%2000==0){
				try {
					TimeUnit.SECONDS.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

 

你可能感兴趣的:(当数据达到2000或者等待5秒后再次运行)