2013-07-02 26 views
0

我不認爲這是可能的,但我想告訴我的每個線程工作在一個特定的對象。有點兒像這樣 -Java如何通過一個線程的額外對象

class Tester implements Runnable{ 
    String s1, s2; 
    Thread t1, t2; 

    test(){ 
     t1 = new Thread(this, "t1"); 
     t2 = new Thread(this, "t2"); 
     t1.start(); 
     t2.start(); 
    } 

    public void run(){ 
     if(this is t1){ 
      s1="s1"; 
     } 
     if(this is t2){ 
      s2="s2"; 
     } 
    } 
} 

我想以某種方式能夠告訴thread t1s2string s1t2運行代碼。現在我只是通過檢查Thread.currentThreat.getName()來做到這一點,但那不是一個好方法。另一種方法是製作一個匿名的Runnable類,它有自己的字符串,並且只有run就可以了,但是接下來主線程如何得到兩個字符串呢?

+0

聲明接口'Worker'用'公共無效的doWork(字符串PARAM)'方法,並將'Worker'在你的類中實現'Runnable'的字段,然後在'run'方法中使用'worker.doWork'。不過,請注意,如果您使用兩個不同的實現'Runnable'接口的類,這可以很容易。 –

回答

8

爲什麼不通過Thread的不同Runnable s?

Runnable r1 = new Runnable() { public void run() { /* this is r1 */ } }; 
Runnable r2 = new Runnable() { public void run() { /* this is r2 */ } }; 
Thread t1 = new Thread(r1); 
Thread t2 = new Thread(r2); 
t1.start(); 
t2.start(); 

/編輯

創建一個類可以實例:

public class MyRunnable implements Runnable { 
    private final String s; 

    public MyRunnable(Stirng s) { 
     this.s = s; 
    } 

    public void run() { 
     // do something with s 
    } 
} 

Thread t1 = new Thread(new MyRunnable("s1")); 
Thread t2 = new Thread(new MyRunnable("s2")); 
t1.start(); 
t2.start(); 

/E2

import java.util.concurrent.Callable; 
import java.util.concurrent.ExecutionException; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.Future; 

public class ExecutorServiceExample { 
    private static class CallableExample implements Callable<Integer> { 
     private final Object foo; 

     private CallableExample(Object foo) { 
      this.foo = foo; 
     } 

     @Override 
     public Integer call() { 
      // do something and return it 
      return foo.hashCode(); 
     } 

    } 

    public static void main(String[] args) throws InterruptedException, ExecutionException { 
     ExecutorService e = Executors.newFixedThreadPool(2); 
     Future<Integer> f1 = e.submit(new CallableExample("foo")); 
     Future<Integer> f2 = e.submit(new CallableExample("bar")); 

     System.out.println(f1.get()); 
     System.out.println(f2.get()); 

     e.shutdown(); 
    } 
} 

Here的對Executor框架一個很好的教程。

+0

我寧願只有一個運行功能(使其他一些事情更容易),但這可以完成。 –

+0

@ Dgrin91除了使用'String'外,兩個'Thread'做的基本相同嗎? – Jeffrey

+0

是的,完全相同的東西,只是在同一個對象的不同實例上。 –

相關問題