[英]Accessing a variable of a thread from another thread in java
我試圖在java中的另一個線程中訪問和修改線程的變量,我真的不知道如何做到這一點。
例如:
Runnable r1 = new Runnable() {
int value = 10;
public void run() {
// random stuff
}
}
Runnable r2 = new Runnable() {
public void run() {
// of course the bellow line will not work
r1.value--; // I want here to be able to decrement the variable "value" of r1
}
}
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
謝謝你,如果你有任何想法!
有沒有辦法在java中為線程創建一個getter和setter?
編輯:答案很好,但我不清楚我的問題,我會嘗試提出一個更好的問題
您可以使其工作,但我建議您使用在線程之間共享的AtomicInteger 。
final AtomicInteger value = new AtomicInteger(10);
Runnable r1 = new Runnable() {
public void run() {
// random stuff using value
}
}
Runnable r2 = new Runnable() {
public void run() {
value.decrementAndGet();
}
}
您可以使用AtomicReference來引用對象。
創建一個runnable,並使用你在runnable中定義的setter和getter。
public class MyRunnable implements Runnable{
private volatile String myString;
public String setString(String value){this.myString = value;}
public String getString(){
return myString;
}
public void run(){}
}
注意此處使用volatile
關鍵字。 volatile關鍵字確保此String在一個線程中發生更改,所有線程都將看到更改。 相反,如果我確保對String對象的唯一訪問是通過同步上下文,則不需要volatile關鍵字。
為了證明我的觀點,上面的代碼和下面的代碼都是線程安全的但是不同,因為在下面的例子中沒有2個線程可以同時輸入setString
和getString
。
public class MyRunnable implements Runnable{
private String myString;
public synchronized String setString(String value){this.myString = value;}
public synchronized String getString(){
return myString;
}
public void run(){}
}
線程實際上只是執行一個runnable。 您可以像這樣使用它:
MyRunnable runnable = new MyRunnable();
Thread myThread = new Thread(runnable);
myThread.start();
String myString = runnable.getString();
使用原語的原子值很好,但如果你想共享一個更復雜的對象,你將不得不閱讀線程和同步。
例如:
public class Stats{
int iterations;
long runtime;
public Stats(){
iterations = 0;
runtime=0;
}
public synchronized void setIterations(int value){this.iterations = value;}
public synchronized void setRuntime(long milliseconds){
this.runtime = milliseconds;
}
public synchronized int getIterations(){
return iterations;
}
public synchronized long getRuntime(){return runtime;}
}
public class StatRunnable implements Runnable{
Stats stats;
boolean active;
public StatRunnable(){
this.active=true;
}
public Stats getStats(){
return stats;
}
long calculateRuntime(){return 0L;}
public void run(){
while(active){
//i'm synchronizing with stats to ensure no other thread alters values
//simultaneously.
synchronized(stats){
stats.setIterations(stats.getIterations()+1);
stats.setRuntime(calculateRuntime());
}
}
}
}
此代碼顯示了通過synchronized
關鍵字與非基本對象同步的示例。 在方法定義中使用synchronized關鍵字將類本身鎖定為同步對象。
最后一點,synchronized關鍵字不僅僅用在方法定義中。 您可以使用它來同步方法中的實例,就像我在StatRunnable
中的run
方法中StatRunnable
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.