[英]Passing parameters to Java Thread
我已經知道: 如何將參數傳遞給Java線程?
但是我不知道該怎么使用。 因此,我簡化了代碼示例,以節省您的寶貴時間:
class ThreadParam implements Runnable {
static int c;
public ThreadParam(int a, int b){
int c = a+b;
}
public void run(){
System.out.println(c);
}
}
public class ThreadParamTest {
public static void main(String args[]){
Runnable r = new ThreadParam(1000,2000);
new Thread(r).start();
}
}
為什么結果為0? 我認為應該是3000。也許變量“ int c”沒有調度到run()方法。 我該如何解決這個問題?
我認為“ static int c”的選擇是不正確的,因為這意味着ThreadParam的所有實例都將“共享”(並且很糟糕)c的通用值。 就是這樣,如果您同時有2個單獨的ThreadParam,則其中之一可能表示C的“錯誤”值。請考慮...
class BadThreadParam implements Runnable {
static int c;
public BadThreadParam( int a, int b ) {
c = a + b;
}
public void run() {
System.out.println( c );
}
}
class ImmutableThreadParam implements Runnable {
private final int c;
public ImmutableThreadParam( int a, int b ) {
c = a + b;
}
public void run() {
System.out.println( c );
}
}
public class BadThreadParamTest {
public static void main( String[] args ) {
BadThreadParam shouldBe3 = new BadThreadParam( 1, 2 );
BadThreadParam shouldBe5 = new BadThreadParam( 3, 2 );
shouldBe3.run(); // Expect 3 but is 5. WTF?
shouldBe5.run(); // Expect 5.
ImmutableThreadParam expect3 = new ImmutableThreadParam( 1, 2 );
ImmutableThreadParam expect5 = new ImmutableThreadParam( 3, 2 );
expect3.run(); // Expect 3.
expect5.run(); // Expect 5.
}
}
如果將“ c”設置為實例本地,則可以解決“ 2個單獨的ThreadParams影響相同值”的問題。 如果將“ private int c”定為final,則可以避免同步。 如果您需要在運行中(或從外部)對“ c”進行突變,那么現在您就進入了同步世界……
class ThreadSafeMutableThreadParam implements Runnable {
private int c;
public ThreadSafeMutableThreadParam( int a, int b ) {
c = a + b;
}
public synchronized void setC( int c ) {
this.c = c;
}
public synchronized int getC() {
return c;
}
public void run() {
System.out.println( getC() );
}
}
除此之外,tuxdna在描述您如何“將參數傳遞給Runnable”方面是正確的。 Runnable無關緊要; 您正在將參數傳遞給課程(無論您如何實現)。 如果需要它們在run()中可用,則需要注意同步。
結果為0,因為在構造函數中,您實際上並未將新值分配給static int c
,而是將其分配給局部變量c
。
在構造函數中將int c
更改為c
。
c
不能是靜態的,應該在構造函數中分配。 在您的示例中,您已分配給變量c
,而不是字段。
這是更正的代碼:
class ThreadParam implements Runnable {
private int c;
public ThreadParam(int a, int b){
this.c = a+b;
}
public void run(){
System.out.println(c);
}
}
您的'c'變量定義了兩次:一次在類級別(帶有靜態修飾符),一次在ThreadParam構造函數中。 刪除類字段上的“靜態”,並刪除構造函數中的“ int”。
Runnable只是一個需要您定義run()
方法的接口,僅此而已。 因此,從本質上講,您可以隨意聲明類構造函數(要傳遞兩個整數a
和b
),以便能夠從run()
方法訪問它們。
另外,您還要在構造函數中定義一個局部變量,該局部變量在構造函數完成后將被銷毀。 這樣您的static int c
值仍為0
。
這是固定版本:
class ThreadParam implements Runnable {
private int c;
public ThreadParam(int a, int b) {
c = a + b;
}
public void run() {
System.out.println(c);
}
}
public class ThreadParamTest {
public static void main(String args[]) {
Runnable r = new ThreadParam(1000, 20000);
new Thread(r).start();
}
}
輸出是21000
(而不是3000
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.