一個LinkedBlockingQueue線程安全的例子
package llj.mf.ace;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
public class Ace {
public static void main(String[] args) throws Exception {
final Queue<Integer> q1 = new LinkedBlockingQueue<>();
final Queue<Integer> q2 = new LinkedBlockingQueue<>();
final int n = 1000000;
final int m = 100;
for (int i = 0; i < n; i++) {
q1.add(i);
}
List<Thread> ts = new ArrayList<>();
for (int i = 0; i < m; i++) {
ts.add(new Thread(new Runnable() {
public void run() {
int i = 0;
while (q2.size() < n && i++ < n / m) { // q2.size() 非線程安全,所以設置每個線程添加平均個數,防止poll出null報錯
q2.add(q1.poll());
}
}
}));
}
for (Thread t : ts) {
t.start();
}
System.out.println("啟動了 " + m + " 個線程,每個線程處理 " + n / m + " 個操作");
for (Thread t : ts) {
while (t.isAlive()) {
Thread.sleep(1);
}
}
System.out.println("q1.size():" + q1.size());
System.out.println("q2.size():" + q2.size());
Set<Integer> set = new HashSet<>();
Integer i;
while ((i = q2.poll()) != null) {
set.add(i);
}
System.out.println("q2.size():" + q2.size());
System.out.println("set.size():" + set.size());
}
}