多线程之ThreadFactory

一般情况下,创建一个线程,常采用三种方式:

1. 继承Thread类

2. 实现Runnable接口

3. 实现Callable接口

现在可以通过ThreadFactory新建线程,ThreadFacotry是线程的工厂类,采用设计模式中的工厂模式,这样我们就可以给该工厂中的所有线程进行统一的管理。

ThreadFactory接口:

public interface ThreadFactory {

    /**
     * Constructs a new {@code Thread}.  Implementations may also initialize
     * priority, name, daemon status, {@code ThreadGroup}, etc.
     *
     * @param r a runnable to be executed by new thread instance
     * @return constructed thread, or {@code null} if the request to
     *         create a thread is rejected
     */
    Thread newThread(Runnable r);
}

JDK实现了一个DefaultThreadFactory

 static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                                  Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                          poolNumber.getAndIncrement() +
                         "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

下面实现一个基于线程工厂的多线程产者和消费者模式:

消息队列

public class Queue {

	private LinkedBlockingQueue<String> queue ;

	public LinkedBlockingQueue<String> getQueue() {
		return queue;
	}

	public void setQueue(LinkedBlockingQueue<String> queue) {
		this.queue = queue;
	}
}


工作线程工厂
public class WorkThreadFactory implements ThreadFactory{

	private static int count;
	
	@Override
	public Thread newThread(Runnable r) {
		return new Thread(r, "线程"+ count++);
	}

}

生产者

public class Producer {

	private volatile int count = 0;
	
	public void start(final Queue queue) {
		WorkThreadFactory factory = new WorkThreadFactory();
		Executor executor = Executors.newFixedThreadPool(5, factory);
		for(int i=0; i<5; i++){
			executor.execute(new Runnable() {
				@Override
				public void run() {
					while(true){
						produce(queue);
						try {
							Thread.sleep(1*100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			});
		}
	}
	
	private String produce(Queue queue){
		try {
			String msg = "消息"+ ++count;
			queue.getQueue().put(msg);
			return msg;
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "";
	}
}

消费者

public class Customer {

	public void start(final Queue queue) {
		WorkThreadFactory factory = new WorkThreadFactory();
		ExecutorService executor = Executors.newFixedThreadPool(5, factory);
		for(int i = 0;i<5; i++){
			executor.execute(new Runnable() {
				@Override
				public void run() {
					while(true){
						customer(queue);
						/*try {
							Thread.sleep(1*1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}*/
					}
				}
			});
		}
	}
	
	private void customer(Queue queue){
		String msg = queue.getQueue().poll();
		if(StringUtils.isNotBlank(msg)){
			System.out.println(Thread.currentThread().getName()+"消费+"+msg);
		}
	}
}

主线程

public class MainThread {

	public static void main(String[] args) {
		Queue queue = new Queue();
		queue.setQueue(new LinkedBlockingQueue<String>());
		Customer customer = new Customer();
		Producer producer = new Producer();
		producer.start(queue);
		customer.start(queue);
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值