我最近在接受采访时被问到这个问题。
编写一个具有两个线程(A 和 B)的程序,其中 A 打印 1 ,B 打印 2 ,依此类推,直到达到 50。
我们该如何去做呢?
分配的本质是演示一个线程如何向另一个线程发出信号。最常见的方法是使用阻塞队列,但这里信号不携带任何信息,因此信号量就足够了。
创建使用 2 个信号量进行参数化的线程类:输入和输出:
class ThreadPrinter implements Runnable {
int counter;
Semaphore ins, outs;
ThreadPrinter(int counter, Semaphore ins, Semaphore outs) {
this.counter = counter;
this.ins = ins;
this.outs = outs;
}
@Override
public void run() {
for (int i = 0; i < 25; i++) {
ins.aquire(); // wait for permission to run
System.out.println("" + counter);
outs.release(); // allow another thread to run
counter += 2;
}
}
创建2个Semaphore
s 并将它们传递给 2 个线程:
Semaphore a = new Semaphore(1); // first thread is allowed to run immediately
Semaphore b = new Semaphore(0); // second thread has to wait
ThreadPrinter tp1 = new ThreadPrinter(1, a, b);
ThreadPrinter tp2 = new ThreadPrinter(2, b, a);
注意信号量a
and b
以不同的顺序传递。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)