通過數組存儲數據
阻塞:
package com.yulang.threadpool.java8;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class Test06 {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue arrayBlockingQueue =new ArrayBlockingQueue(3,false);
new Thread(()->{
while (true) {
System.out.println(arrayBlockingQueue.poll());
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
for(int i=0;i<6;i++){
new Thread(()->{
try {
arrayBlockingQueue.put(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
TimeUnit.SECONDS.sleep(10);
}
}
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
notFull.await();
enqueue(e);
} finally {
lock.unlock();
}
}
非阻塞:
package com.yulang.threadpool.java8;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class Test06 {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue arrayBlockingQueue =new ArrayBlockingQueue(3,false);
new Thread(()->{
while (true) {
System.out.println(arrayBlockingQueue.poll());
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
for(int i=0;i<6;i++){
new Thread(()->{
arrayBlockingQueue.offer(Thread.currentThread().getName());
}).start();
}
TimeUnit.SECONDS.sleep(10);
}
}