- 创建个性化线程。如本案例所示,使用特殊格式来命名,甚至可以通过继承Thread类来创建自己的线程类。
- 如前面案例所示,保存创建线程的统计信息。
- 限制线程创建数量。
- 验证线程的创建。
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
import java.util.List;
* 线程工厂
*
* @since 2024-10-26 23:16:30
*/
public class MyThreadFactory implements ThreadFactory {
private int counter;
private String name;
private List<String> stats;
private AtomicLong threadNum = new AtomicLong();
public MyThreadFactory(String name) {
this.counter = 0;
this.name = name;
this.stats = new ArrayList<>();
}
@Override
public Thread newThread(Runnable r) {
counter++;
stats.add(String.format("Thread #%d: %s", counter, name));
return new Thread(r, "my-thread-" + threadNum.incrementAndGet());
}
* 返回一个字符串,该字符串包含了线程工厂创建的所有线程的统计信息
*
* @return 一个字符串,该字符串包含了线程工厂创建的所有线程的统计信息
*/
public String getStats() {
StringBuffer buffer = new StringBuffer();
Iterator<String> it = stats.iterator();
while (it.hasNext()) {
buffer.append(it.next());
buffer.append("\n");
}
return buffer.toString();
}
private static class Task implements Runnable {
@Override
public void run() {
System.out.println("hello world");
}
}
public static void main(String[] args) {
MyThreadFactory factory = new MyThreadFactory("MyThreadFactory");
Thread thread = factory.newThread(new Task());
thread.start();
System.out.println(factory.getStats());
}
}