0

このコードでRunnableにIDを設定するにはどうすればよいですか

Runnable rd = new Runnable() {
    @Override
    public void run() {
        populatePanel(referList.get(handler.getPosition()), handler.getPosition());
        if (i == referList.size() - 1) {
            i = 0;
        }
    }
};
handler.postDelayed(rd, delay);

スレッドを他のスレッドと区別したい

4

4 に答える 4

5

Runnable ではなくスレッドに名前を設定します。たとえば、次のようにします。

    RunnableJob runnableJob = new RunnableJob();

    Thread thread1 = new Thread(runnableJob);
    thread1.setName("thread1");
    thread1.start();

    Thread thread2 = new Thread(runnableJob, "thread2");
    thread2.start();

    Thread thread3 = new Thread(runnableJob);
    thread3.start();

    Thread currentThread = Thread.currentThread();
    System.out.println("Main thread: " + currentThread.getName() + "(" +currentThread.getId() + ")");

これにより、次のように出力されます。

RunnableJob is being run by thread1 (11)
RunnableJob is being run by thread2 (12)
Main thread: main(1)
RunnableJob is being run by Thread-1 (13)

ソースはこちら

于 2013-07-08T09:30:53.827 に答える
0

匿名サブクラスを作成しています。サブクラス化に関しては、特別なことは何もありません。たとえばprivate final int ID = 42、クラスにフィールドを簡単に追加して、run メソッド内またはメソッド内でそのフィールドを使用できますtoString。ただし、パブリック API を追加する必要がある場合、匿名クラスは使用できませんが、代わりに別のインターフェイスを実装する内部クラスを使用できます。

于 2013-07-08T09:31:04.837 に答える
0

Create inner class with instance id.

handler.postDelayed(new MyRunnable(1), delay);  
handler.postDelayed(new MyRunnable(2), delay);




class MyRunnable implements Runnable{    
  long id;  
  public MyRunnable(long id){  
this.id = id;  
}
  @Override  
    public void run() {  
        populatePanel(referList.get(handler.getPosition()), handler.getPosition());  
        if (i == referList.size() - 1) {  
            i = 0;  
        }  
    }

}
于 2013-07-08T09:35:10.260 に答える