[英]Sharing the same data area in JAVA multithreading?
據說,如果一個類實現為Runnabe接口,則可以將其變成一個線程,該線程的實例可以共享該類中的相同數據區域。 但是,在Runnable接口中只有run()方法,那么如何實現呢?
@La Kate,共享發生在implements Runnable
的具體類中。 這樣的類將具有state ,即包含有關Runnable
實例的信息的字段。 這些字段在使用完全相同的Runnable
實例的每個線程之間共享。 這與錯誤地extends Thread
慣用法不同,在后者中,每個線程都有自己單獨的狀態。
因此,例如:
final Runnable runnable = new Runnable() {
final Object lock = new Object();
final ImportantInfo info = new ImportantInfo();
@Override
public void run() {
while (true) {
doABunchOfStuff();
synchronized (lock) {
info.load();
}
doABunchOfOtherStuff();
}
}
};
此Runnable
實例可以發送到多個Thread
:
Thread footh = new Thread(runnable);
Thread barth = new Thread(runnable);
footh.start();
barth.start();
這兩個線程使用完全相同的Runnable
,這意味着每個線程現在都通過不可變的lock
對象和可變info
對象共享狀態。 前者可以同步訪問,而后者可以在線程之間傳遞更改。
但是,在Runnable接口中只有run()方法,那么如何實現呢?
這是通過在可運行對象中引入狀態,然后為這些狀態對象傳遞相同的實例來實現的。 沒有狀態的可運行對象不會共享數據。
以下不是正在運行或正在編譯的代碼,而只是給您一個大概的想法-有兩個線程共享一個Student
對象。 private Student student;
向您的可運行狀態引入狀態。
public class ExampleRunnable implements Runnable {
private Student student;
public void ExampleRunnable(Student student){
this.student=student;
}
@Override
public void run(){
.....do something with student here in synchronized way....
.....
}
下面是您創建線程的類,
public class MainClass {
public static void main(String[] args){
Student student = new Student();
Thread thread1 = new Thread(new ExampleRunnable(student));
Thread thread2 = new Thread(new ExampleRunnable(student));
/* So in above code, there are two different runnables and two different threads but both are using same Student object . This way you can share data among various runnables / threads. */
}
}
}
實際上,Runnable接口僅提供一種將對象轉換為線程的方法(它是一個接口),它不是共享變量的結構,這些對象可以使用“同步”修飾符或其他線程安全的結構共享變量(您可以找到它在oracle指南中),但這取決於您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.