自定义线程,构造时指定当前线程具备的参数。
通过 Thread.currentThread(); 获取所属的线程对象,当是指定类型进行类型转换,从而获取对应线程的线程参数。
具体示例如下:
import org.junit.Test;
public class ThreadParamTest {
static class MyService {
public void showCurrentThread() {
Thread currentThread = Thread.currentThread();
System.out.println("ThreadClass:" + currentThread.getClass().getName());
if (currentThread instanceof MyThread) {
MyThread current = (MyThread) currentThread;
String param = current.getParam();
System.out.println(String.format("Thread:%s Thread Param:%s", current.getId(), param));
}
}
}
static class MyThread extends Thread {
private final MyService service;
private String param;
public MyThread(String param, MyService service) {
this.service = service;
this.param = param;
}
public String getParam() {
return this.param;
}
@Override
public void run() {
service.showCurrentThread();
}
}
@Test
public void test() throws InterruptedException {
MyService service = new MyService();
service.showCurrentThread();
new MyThread("Param_1", service).start();
new MyThread("Param_2", service).start();
new MyThread("Param_3", service).start();
Thread.sleep(5000);
}
}