ThreadFactory
大约 1 分钟
1、
package com.yootk;
public class YootkDemo { // 李兴华高薪就业编程训练营
public static void main(String[] args) { // 沐言科技:www.yootk.com
for (int x = 0; x < 100; x++) {
new Thread(()->{
System.out.println("线程名称:" + Thread.currentThread().getName());
}).start();
}
}
}
2、
package com.yootk;
import java.util.concurrent.ThreadFactory;
class YootkThreadFactory implements ThreadFactory { // 创建线程工厂类
private static final ThreadFactory INSTANCE = new YootkThreadFactory();
private static final String TITLE = "yootk-"; // 定义线程名称的开头
private static int count = 0; // 线程的自动计数处理
private YootkThreadFactory() {} // 工厂类在定义的时候一定不需要实例化对象
public static ThreadFactory getInstance() { // 返回工厂实例
return INSTANCE;
}
@Override
public Thread newThread(Runnable r) { // 此时的操作如果有需要可以进一步改进,例如:通过反射
return new Thread(r, TITLE + count++); // 实例化Thread类对象
}
}
public class YootkDemo { // 李兴华高薪就业编程训练营
public static void main(String[] args) { // 沐言科技:www.yootk.com
for (int x = 0; x < 10; x++) {
Thread thread = YootkThreadFactory.getInstance().newThread(() -> {
System.out.println("多线程执行:" + Thread.currentThread().getName());
});
thread.start();
}
}
}
3、
package com.yootk;
import java.lang.reflect.Constructor;
import java.util.concurrent.ThreadFactory;
class YootkThreadFactory implements ThreadFactory { // 创建线程工厂类
private static final ThreadFactory INSTANCE = new YootkThreadFactory();
private static final String TITLE = "yootk-"; // 定义线程名称的开头
private static int count = 0; // 线程的自动计数处理
private YootkThreadFactory() {} // 工厂类在定义的时候一定不需要实例化对象
public static ThreadFactory getInstance() { // 返回工厂实例
return INSTANCE;
}
@Override
public Thread newThread(Runnable r) { // 此时的操作如果有需要可以进一步改进,例如:通过反射
try {
Class<?> clazz = Class.forName("java.lang.Thread");
Constructor<?> constructor = clazz.getConstructor(Runnable.class, String.class);
return (Thread) constructor.newInstance(r, TITLE + count++); // 实例化Thread类对象
} catch (Exception e){
return null;
}
}
}
public class YootkDemo { // 李兴华高薪就业编程训练营
public static void main(String[] args) { // 沐言科技:www.yootk.com
for (int x = 0; x < 10; x++) {
Thread thread = YootkThreadFactory.getInstance().newThread(() -> {
System.out.println("多线程执行:" + Thread.currentThread().getName());
});
thread.start();
}
}
}
demo