如何在这段代码中在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);
我想将一个线程与另一个线程区分开
最佳答案
您在线程上而不是在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)
来源here。