1 import java.util.ArrayList; 2 import java.util.List; 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 import java.util.concurrent.CopyOnWriteArrayList; 6 7 public class TestCalc { 8 /** 9 *read 10 */ 11 private static class ReadTask implements Runnable { 12 List<String> list; 13 14 public ReadTask(List<String> list) { 15 this.list = list; 16 } 17 18 public void run() { 19 for (String str : list) { 20 System.out.println(str); 21 } 22 } 23 } 24 /** 25 *write 26 * 27 */ 28 private static class WriteTask implements Runnable { 29 List<String> list; 30 int index; 31 32 public WriteTask(List<String> list, int index) { 33 this.list = list; 34 this.index = index; 35 } 36 37 public void run() { 38 list.remove(index); 39 list.add(index, "write_" + index); 40 } 41 } 42 43 public void run() { 44 final int NUM = 10; 45 //List<String> list = new ArrayList<String>(); //java.util.ConcurrentModificationException 46 CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>(); 47 for (int i = 0; i < NUM; i++) { 48 list.add("main_" + i); 49 } 50 ExecutorService executorService = Executors.newFixedThreadPool(NUM); 51 for (int i = 0; i < NUM; i++) { 52 executorService.execute(new ReadTask(list)); 53 executorService.execute(new WriteTask(list, i)); 54 } 55 executorService.shutdown(); 56 } 57 58 public static void main(String[] args) { 59 new TestCalc().run(); 60 } 61 } 62 63 /* 64 65 //List<String> list = new ArrayList<String>(); 66 Exception in thread "pool-1-thread-11" java.util.ConcurrentModificationException 67 68 at java.util.ArrayList$Itr.checkForComodification(Unknown Source) 69 at java.util.ArrayList$Itr.next(Unknown Source) 70 at TestCalc$ReadTask.run(TestCalc.java:19) 71 at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) 72 at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) 73 at java.lang.Thread.run(Unknown Source) 74 */
时间: 2024-10-25 02:27:48