[英]synchronized across classes in java
我有兩個並發運行的線程,一個主線程和一個舊的布爾變量類,我目前有一個thrad打印賠率和其他打印平均值,但我讓他們等待彼此,以便打印1 - 100順序。
我目前正在我的NumberPrinter類中引用一個布爾對象,我正在使用它來使一個線程進入等待狀態等待另一個。 我知道如何在同一個類中進行同步,但是當我嘗試跨線程進行同步時,它只是掛起並且看起來布爾變量沒有被更新或與兩個線程同步。 至少這就是我認為是問題的原因
謝謝任何建議表示贊賞
我的考試班
public class Test {
public static void main(String[] args) throws InterruptedException {
NumberPrinter np = new NumberPrinter();
single ent = new single(np);// new state
Double ont = new Double(np);// new state
ent.start();
ont.start();
}
}
甚至是上課
public class single extends Thread {
private NumberPrinter printer;
public single(NumberPrinter np) {
this.printer = np;
}
public synchronized void run() {
try {
for (int i = 1; i <= 100; i++) {
System.out.println(printer.isOdd);
if (i % 2 == 0) {
if (printer.isOdd == true) {
wait();
}
System.out.println(i);
printer.isOdd = true;
notifyAll();
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
奇數類
public class Double extends Thread {
private NumberPrinter printer;
public Double(NumberPrinter np) {
this.printer = np;
}
public synchronized void run() {
try {
for (int i = 1; i <= 100; i++) {
System.out.println(printer.isOdd);
if (i % 2 == 1) {
if (printer.isOdd == false) {
wait();
}
System.out.println(getName() + ": " + i);
printer.isOdd = false;
notifyAll();
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
一個保存布爾變量的類
package single;
public class NumberPrinter {
public boolean isOdd = true;
}
需要在兩個線程的同一個對象上調用wait
和notifyAll
。 您還需要同步該對象。 您正在使用線程實例,但有兩個不同的實例。 您可以使用printer
對象,或者您可以創建一個new Object()
並使用它。 wait
也應該在while循環中使用而不是if語句。
public void run() {
try {
for (int i = 1; i <= 100; i++) {
synchronized(printer) {
System.out.println(printer.isOdd);
if (i % 2 == 1) {
while (printer.isOdd == false) {
printer.wait();
}
System.out.println(getName() + ": " + i);
printer.isOdd = false;
printer.notifyAll();
}
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.