public class Test2 extensions Thread{ private static Object s1; static void p1() { System.out.println(“1”); } static void p2() { System.out.println(“2”); } static void p3() { System.out.println(“3”); } static void p4() { System.out.println(“4”); } static void p5() { System.out.println(“5”); } static void p6() { System.out.println(“6”); } public void run() { p1(); p2(); p3(); p4(); p5(); p6(); } public static void main(String[] args) 抛出 InterruptedException { Semaphore s1=new Semaphore(1); 线程 t1=new 线程(()->Test2.p1());线程 t2=new 线程(()->Test2.p2());线程 t3=new Thread(()->Test2.p3());线程 t4=new Thread(()->Test2.p4());线程 t5=new Thread(()->Test2.p5());线程 t6=new 线程(()->Test2.p6());t1.start();t2.start();t3.start();t4.start();t5.start();t6.start();t1.join();t2.join();t3.join();t4.join();t5.join();t6.join();} }怎样添加信号量实现输出结果为1 4 3 2 5 6
时间: 2023-10-28 13:05:49 浏览: 107
.Net 3.5 使用 System.Threading.Task
要使用信号量实现输出结果为1 4 3 2 5 6,可以在每个静态方法中添加获取和释放信号量的操作。首先在main函数中创建一个Semaphore对象,初值为0,表示没有线程可以进入Semaphore所控制的代码段。然后在每个静态方法中,首先获取Semaphore的许可,如果许可不足则等待,然后执行相应的输出语句,最后释放Semaphore的许可。按照这种方式,可以保证输出结果为1 4 3 2 5 6。修改后的代码如下:
```
import java.util.concurrent.Semaphore;
public class Test2 extends Thread {
private static Semaphore s1 = new Semaphore(0);
static void p1() {
try {
s1.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1");
}
static void p2() {
System.out.println("2");
s1.release();
}
static void p3() {
try {
s1.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("3");
}
static void p4() {
System.out.println("4");
s1.release();
}
static void p5() {
try {
s1.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("5");
}
static void p6() {
System.out.println("6");
s1.release();
}
public void run() {
p1();
p2();
p3();
p4();
p5();
p6();
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> Test2.p1());
Thread t2 = new Thread(() -> Test2.p2());
Thread t3 = new Thread(() -> Test2.p3());
Thread t4 = new Thread(() -> Test2.p4());
Thread t5 = new Thread(() -> Test2.p5());
Thread t6 = new Thread(() -> Test2.p6());
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
t6.join();
}
}
```
阅读全文