public class Test extends Thread { static int x=0; public static void a(){ x++; System.out.println(x); } public void run(){ a(); } public static void main(String[] args) throws InterruptedException { Thread t1=new Thread(()->Test.a()); Thread t2=new Thread(()->Test.a()); Thread t3=new Thread(()->Test.a()); Thread t4=new Thread(()->Test.a()); Thread t5=new Thread(()->Test.a()); t1.start(); t1.join(); t2.start(); t2.join(); t3.start(); t3.join(); t4.start(); t4.join(); t5.start(); t5.join(); } }用信号量实现输出总为5
时间: 2024-01-27 10:02:36 浏览: 78
可以使用信号量来限制同时执行 `a()` 方法的线程数量,从而保证输出总为5。代码如下:
```
import java.util.concurrent.Semaphore;
public class Test extends Thread {
static int x = 0;
static Semaphore semaphore = new Semaphore(1);
public static void a() {
try {
semaphore.acquire();
x++;
System.out.println(x);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
public void run() {
a();
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> Test.a());
Thread t2 = new Thread(() -> Test.a());
Thread t3 = new Thread(() -> Test.a());
Thread t4 = new Thread(() -> Test.a());
Thread t5 = new Thread(() -> Test.a());
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
}
}
```
在 `a()` 方法中,使用 `semaphore.acquire()` 申请信号量,如果已经有5个线程在执行,则会被阻塞,直到有一个线程执行完毕后释放信号量。同时在 `finally` 中释放信号量。这样就可以保证同时只有最多5个线程在执行 `a()` 方法,从而保证输出总为5。
阅读全文