public class Test1 extends Thread{ static int data[]=new int[5]; static Semaphore s1=new Semaphore(1); static void put(int num) { try { s1.acquire(); for(int i=0;i<5;i++) { data[i]=num; } s1.release(); } catch (InterruptedException e) { throw new RuntimeException(e); } } public void run() { put(2); put(5); put(0); } public static void main(String[] args) { Thread t1=new Thread(()->Test1.put(2)); Thread t2=new Thread(()->Test1.put(5)); Thread t3=new Thread(()->Test1.put(0)); t1.start(); t2.start(); t3.start(); try { t1.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { t2.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } try { t3.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } try { s1.acquire(); for(int j=0;j<5;j++) { System.out.println(data[j]); } s1.release(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }将这段代码修改为输出结果总是5
时间: 2024-01-26 14:02:07 浏览: 69
要让输出结果总是5,可以将put()方法中的for循环改为只给数组的第一个元素赋值为num。此外,需要将Semaphore的许可证数量改为5,确保只有当所有数据都被写入数组后,才能进行输出操作。修改后的代码如下:
```
public class Test1 extends Thread {
static int data[] = new int[5];
static Semaphore s1 = new Semaphore(5);
static void put(int num) {
try {
s1.acquire();
data[0] = num;
s1.release();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void run() {
put(2);
put(5);
put(0);
}
public static void main(String[] args) {
Thread t1 = new Thread(() -> Test1.put(2));
Thread t2 = new Thread(() -> Test1.put(5));
Thread t3 = new Thread(() -> Test1.put(0));
t1.start();
t2.start();
t3.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
t2.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
t3.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
s1.acquire(5);
for (int j = 0; j < 5; j++) {
System.out.println(data[j]);
}
s1.release(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
```
输出结果将总是5。
阅读全文