[英]Passing variable into methods (Java)
我是Java的新手,但我遇到了問題。 我已經從Android教程中復制了一些代碼,現在我想將整數變量傳遞到方法run()中,這樣我可以為每個循環遞增它,然后在后台線程之外捕獲它。 我該怎么做?
int gg= 0;
Thread background = new Thread(new Runnable() {
public void run() {
try {
while (pBarDialog.getProgress() <= 100) {
Thread.sleep(100);
gg++; // the increment here
progressHandler.sendMessage(progressHandler
.obtainMessage());
}
if (pBarDialog.getProgress() == 100) {
pBarDialog.dismiss();
}
} catch (java.lang.InterruptedException e) {
// if something fails do something smart
}
}
});
//catch gg here
您不能為run()方法指定參數。 您可以將int變量聲明為字段,並在內部類中使用它。
public class TestActivity extends Activity
{
private volatile int no;
.....
}
編輯:(來自@alf的建議)您可以將volatile
修飾符與字段一起使用,以便所有其他線程可以立即看到更改的值。
有一個自己的類,並使用其構造函數傳遞計數器,我還沒有嘗試過,但是我將從這樣的事情開始:
class MyThread implements Runnable {
private volatile int counter;
public MyThread( int counter ) {
this.counter = counter;
}
public void run() {
...
}
public getCounter() {
return counter;
}
}
MyThread mt = new MyThread( 10 );
Thread t = new Thread( mt );
t.start();
// after some time
t.getCounter();
private volatile int gg;
public void myMethod() {
Thread background = new Thread(new Runnable() {
@Override
public void run() {
try {
while (pBarDialog.getProgress() <= 100) {
Thread.sleep(100);
gg++; // the increment here
progressHandler.sendMessage(progressHandler.obtainMessage());
}
if (pBarDialog.getProgress() == 100) {
pBarDialog.dismiss();
}
} catch (java.lang.InterruptedException e) {
// if something fails do something smart
}
}
});
System.out.println(gg);
}
如果我是您,那么我將研究AtomicInteger ,即incrementAndGet()
AndGet incrementAndGet()
方法。
將gg
為字段確實可以使線程訪問 gg
,而volatile
可以使更改可見,但是由於您的意圖不明確,因此我無法確定您沒有其他線程增加相同的值:您沒有具有原子性,因此一旦有多個線程在執行gg++
,就很可能會得到錯誤的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.