题目:
启动若干线程,并行访问同一个容器中的数据。保证获取容器中数据时没有数据错误,且线程安全。如:售票,秒杀等业务。
import java.util.ArrayList; import java.util.List; public class Test_01 { static List<String> list = new ArrayList<>(); // static List<String> list = new Vector<>(); static { for (int i = 0; i < 10000; i++) { list.add("String " + i); } } public static void main(String[] args) { for (int i = 0; i < 10; i++) { new Thread(new Runnable() { @Override public void run() { while (list.size() > 0) { System.out.println(Thread.currentThread().getName() + " - " + list.remove(0)); } } }, "Thread" + i).start(); } // for(int i = 0; i < 10; i++){ // new Thread(new Runnable() { // @Override // public void run() { // while(true){ // synchronized (list) { // if(list.size() <= 0){ // break; // } // System.out.println(Thread.currentThread().getName() + " - " + list.remove(0)); // } // } // } // }, "Thread" + i).start(); // } } }
import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; public class Test_02 { static Queue<String> list = new ConcurrentLinkedQueue<>(); static { for (int i = 0; i < 10000; i++) { list.add("String " + i); } } public static void main(String[] args) { for (int i = 0; i < 10; i++) { new Thread(new Runnable() { @Override public void run() { while (true) { String str = list.poll(); if (str == null) { break; } System.out.println(Thread.currentThread().getName() + " - " + str); } } }, "Thread" + i).start(); } } }
Stay hungry,stay foolish !