use*_*434 7 java concurrency multithreading
最近我在接受采访时被问到了这个问题.
编写一个带有两个线程(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;
}
}
Run Code Online (Sandbox Code Playgroud)
创建2 Semaphore秒并将它们传递给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);
Run Code Online (Sandbox Code Playgroud)
注意信号量a并b以不同的顺序传递.
这是另一个解决方案:
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
for (int i = 1; i <= 50; i += 2) {
System.out.println("T1=" + i);
t1turn = false;
try {
lock.notifyAll();
lock.wait();
} catch (InterruptedException e) {
}
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
for (int i = 2; i <= 50; i += 2) {
if (t1turn)
try {
lock.wait();
} catch (InterruptedException e) {
}
System.out.println("T2=" + i);
t1turn = true;
lock.notify();
}
}
}
});
t1.start();
t2.start();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27610 次 |
| 最近记录: |