问题:定时任务获取一个列表list,该list数据有增有减,有两个线程需要遍历该list,得到每个实例数据,代码如下,问题是对list加上volatile或者修改list为Collections.synchronizedList,代码无异常,下面的代码有哪些bug呢
代码:
import java.util.*; public class TestList { static List<Integer> list = new ArrayList<>(); static Random rand = new Random(47); static class Task extends TimerTask { public void run() { synchronized (list) { System.out.println("timer"); list.clear(); int n = rand.nextInt(100); for (int i = 0; i < n; i++) { list.add(i); } } } } static class MyThread extends Thread { MyThread(String name) { super(name); } public void run() { while (true) { for (int i = 0, n = list.size(); i < n; i++) { synchronized (list) { if (i < list.size()) { System.out.println(getName() + "," + list.get(i)); } else { break; } } } } } } public static void main(String[] args) { MyThread t1 = new MyThread("t1"); MyThread t2 = new MyThread("t2"); t1.start(); t2.start(); Task task = new Task(); Timer timer = new Timer(); timer.schedule(task, 0, 30); } }
项目:JFinal