介绍
简单来说就是用来创建线程的,其中也只是有一个newthread方法
一些常用的作用
- 给线程命名,查看创建线程数
- 给线程设置是否是后台运行
- 设置线程优先级
示例
- MyThreadFactory
package com.demo.factory;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by Administrator
*/
public class MyThreadFactory implements ThreadFactory{
private AtomicInteger atomicInteger = new AtomicInteger();
private boolean isDaemon;
public MyThreadFactory(boolean isDaemon){
this.isDaemon = isDaemon;
}
@Override
public Thread newThread(Runnable r) {
atomicInteger.incrementAndGet();
Thread thread = new MyWorkThread(atomicInteger,r);
thread.setDaemon(isDaemon);
return thread;
}
}
- MyWorkThread
package com.demo.factory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by Administrator
*/
public class MyWorkThread extends Thread{
private AtomicInteger atomicInteger;
public MyWorkThread(AtomicInteger atomicInteger,Runnable runnable){
super(runnable);
this.atomicInteger = atomicInteger;
}
@Override
public void run() {
System.out.println(this.getName()+" test"+atomicInteger.getAndDecrement());
super.run();
}
}
- TestMain
package com.demo.factory;
import java.util.concurrent.*;
/**
* Created by Administrator
*/
public class TestMain {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool(new MyThreadFactory(false));
for (int i=0;i<1000;i++){
executorService.execute(new TestRunnable(String.valueOf(i)));
}
executorService.shutdown();
}
static class TestRunnable implements Runnable{
private String msg;
public TestRunnable(String msg){
this.msg = msg;
}
@Override
public void run() {
System.out.println("runnable:"+msg);
}
}
}
网友评论