使用“生產(chǎn)者-消費者模式”編寫代碼實現(xiàn):線程A隨機間隔(10~200ms)按順序生成1到100的數(shù)字(共100個)忿薇,
放到某個隊列中.線程B、C苟穆、D即時消費這些數(shù)據(jù)妓忍,線程B消費所有被3整除的數(shù),
線程C消費所有被5整除的數(shù)尝苇,其它的由線程D進行消費铛只。線程BCD消費這些數(shù)據(jù)時在控制臺中打印出來,
要求按順序打印這些數(shù)據(jù)
限時40分鐘糠溜,可以查API
當(dāng)時我用了blockQueue去實現(xiàn)淳玩,沒有實現(xiàn)出來,后來被面試官問的啞口無言非竿,下面是自己查閱資料蜕着,并請教了我公司老大,最后給整理出來的代碼红柱。后來覺的我老大給我說的很受用承匣,這種題一只要把題目給分析清楚了(主要考察多線程之間的相互通訊,使用lock的多路通知)锤悄,一般這種題都是會有坑的韧骗,千萬不要跳進去。另外零聚,java并發(fā)包里面的的東西真的很重要袍暴。
import java.util.LinkedList;
import java.util.PrimitiveIterator;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test {
static class MyQueue {
private Queue<Integer> queue = new LinkedList<>();
private PrimitiveIterator.OfLong longs = new Random().longs(10, 200).iterator();
private Lock lock = new ReentrantLock();
private Condition b = lock.newCondition();
private Condition c = lock.newCondition();
private Condition d = lock.newCondition();
public int b_pull() {
lock.lock();
try {
try {
b.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
lock.unlock();
}
return queue.remove();
}
public int c_pull() {
lock.lock();
try {
try {
c.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
lock.unlock();
}
return queue.remove();
}
public int d_pull() {
lock.lock();
try {
try {
d.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
lock.unlock();
}
return queue.remove();
}
public void start() {
new Thread(() -> {
for (int i = 1; i <= 100; i++) {
queue.add(i);
lock.lock();
try {
if (i % 3 == 0) {
b.signal();
} else if (i % 5 == 0) {
c.signal();
} else {
d.signal();
}
} finally {
lock.unlock();
}
try {
TimeUnit.MILLISECONDS.sleep(longs.nextLong());
} catch (InterruptedException ignore) {
}
}
System.out.println("all numbers are produced.");
}).start();
}
}
public static void main(String[] args) {
MyQueue queue = new MyQueue();
new Thread(() -> {
while (true) {
System.out.println(String.format("B(mod 3) consume : %d", queue.b_pull()));
}
}).start();
new Thread(() -> {
while (true) {
System.out.println(String.format("C(mod 5) consume : %d", queue.c_pull()));
}
}).start();
new Thread(() -> {
while (true) {
System.out.println(String.format("D(other) consume : %d", queue.d_pull()));
}
}).start();
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
queue.start();
}
}