-2
class decrypt implements Runnable {
String name = "decode";
String text;
Thread t;
boolean ok = true;
boolean done = false;
decrypt(String en) {
t = new Thread(this, name);
System.out.println("Thread " + t.getName() + " Started!");
this.text = en;
}
decrypt() {
t = new Thread(this, "Main");
}
void ok(){
this.ok=true;
}
synchronized public void run() {
try {
Random rand = new Random();
System.out.println("Enter password");
Scanner input = new Scanner(System.in);
String p=input.next();
String fs = text.replace(p, "").trim();
System.out.println("Decrypting in progress.....");
t.sleep(500);
System.out.println("Original form of '" + text + "' is :'" + fs + "'");
ok();
System.out.println("");
done=true;
}catch (Exception e){
System.out.println("I handled an error for you, don't worry!");
}
}
}
主營:
..........
decrypt mm=new decrypt();
String sd="";
int itmessss=0;
while (!sd.equals("0")){
if(mm.ok) { // at first time true, then always false!!
mm.t = new Thread(new decrypt(sd));
System.out.println("Please wait...");
mm.t.start();
}
}
......... 。
爲什麼
void ok(){
this.ok=true;
}
這不會設置mm.ok
到true
,它首先是真的,然後總是假!
我也試過這樣:
System.out.println("Original form of '" + text + "' is :'" + fs + "'");
this.ok=true;
System.out.println("");
done=true;
我不知道爲什麼,這並不工作,調用者(線程)總是把它讀成假
任何幫助,將不勝感激
請exaplain,我是新來的Java。我在哪裏做什麼? – 11111111188u9u98
聲明你的變量ok爲volatile boolean ok = true ;.編譯器和VM以其他方式優化訪問權限。如果沒有聲明爲volatile,它將被「緩存」。 –
請參閱我已編輯的文章中的鏈接。 –