Thread pools and work queues

本文介绍了线程池的基本原理,包括线程池如何维护多个线程并利用队列分配任务,以及其实现细节。此外,还提供了一个简单的Java线程池实现案例,展示了如何创建任务、接收任务和处理任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.ibm.com/developerworks/library/j-jtp0730/index.html

 

线程池的原理:

1. 内部维护若干个线程,这些线程一直保持运行/阻塞状态;

2. 维护一个队列,通过锁的方式让这些线程从队列中取任务;

3. 如果队列没有任务,则阻塞当前请求任务的线程;

4. 当有新的任务加入到任务队列时,唤醒与锁绑定的等待集中的线程

这就是线程池最基本的原理!

 

package thread;

import java.util.LinkedList;

public class WorkQueue {
	
	private final int nThreads;
	private final PoolWorker[] threads;
	private final LinkedList queue;
	
	public WorkQueue(int nThreads) {
		this.nThreads = nThreads;
		threads = new PoolWorker[nThreads];
		queue = new LinkedList();
		
		for(int i=0; i<nThreads; i++) {
			threads[i] = new PoolWorker("worker-" + i);
			threads[i].start();
			System.out.println(threads[i].getName()+" starts to work");
		}
	}
	
	//面向接口进行设计,只要是实现Runnable接口的任务都可以被接收
	public void execute(Runnable task) {
		synchronized(queue) {
			queue.add(task);
			System.out.println("$$$ current tasks:" + queue.size());
			queue.notify();
		}
	}
	
	//worker的任务:处理任务队列 Task Queue 中的任务
	private class PoolWorker extends Thread {
		
		public PoolWorker(String threadName) {
			super(threadName);
		}
		
		public void run() {
			Runnable task;
			for(;;) {
				synchronized (queue) {
					while(queue.isEmpty()) {
						try {
							System.out.println("there is no task! "+Thread.currentThread().getName() + " is waiting...");
							queue.wait();
						} catch (InterruptedException ignored) {}
					}
					//取出任务
					task = (Runnable)queue.removeFirst();
				}
				try{
					task.run();
				} catch(RuntimeException e) {
					//log something here
				}
			}
		}
	}
}

 

 

package thread;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 实现Runnable表示此类为任务类
 *
 */
public class FileSaver implements Runnable {
	
	private File file;
	
	public FileSaver(File file) {
		this.file = file;
	}

	@Override
	public void run() {
		try {
			long mills = new Random().nextInt(10000);
			Thread.sleep(mills);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
			System.out.println(Thread.currentThread().getName() + ": Write file to disk at " + sdf.format(new Date()) + "--->" + file.getName() + ", takes " + mills + " ms");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}

 

 

package thread;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;

public class Client {
	public static void main(String[] args) {
		//系统启动便初始化工作队列
		WorkQueue queue = new WorkQueue(2);
		
		//模拟客户端请求
		Random rand = new Random();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		int i = 1;
		while(true) {
			try {
				Thread.sleep(rand.nextInt(5000));
				String fileName = "file"+(i++);
				System.out.println("One request arrive at " + sdf.format(Calendar.getInstance().getTime()) + ", fileName=" + fileName);
				File file = new File(fileName);
				FileSaver saver = new FileSaver(file);
				queue.execute(saver);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}

 

 

BUG: workqueue lockup - pool cpus=0 node=0 flags=0x0 nice=0 stuck for 31s! Showing busy workqueues and worker pools: workqueue events: flags=0x0 pwq 10: cpus=5 node=0 flags=0x0 nice=0 active=2/256 refcnt=3 in-flight: 21012:update_ptp_local_sec_work [jlsemiautophy] pending: kfree_rcu_monitor pwq 8: cpus=4 node=0 flags=0x0 nice=0 active=1/256 refcnt=2 in-flight: 19893:i2c_check_workq [ti_ds90ub983] pwq 0: cpus=0 node=0 flags=0x0 nice=0 active=7/256 refcnt=8 in-flight: 6269:rx_timestamp_work [jlsemiautophy] pending: kernfs_notify_workfn, vmstat_shepherd, free_work, check_ipc [carevent_wt], kfree_rcu_monitor, psi_avgs_work workqueue events_unbound: flags=0x2 pwq 12: cpus=0-5 flags=0x4 nice=0 active=3/512 refcnt=5 in-flight: 17802:toggle_allocation_gate, 21203:mmstat_work_handler [trace_mmstat] mmstat_work_handler [trace_mmstat] workqueue events_power_efficient: flags=0x80 pwq 0: cpus=0 node=0 flags=0x0 nice=0 active=8/256 refcnt=9 pending: do_cache_clean, neigh_managed_work, neigh_managed_work, neigh_periodic_work, neigh_periodic_work, gc_worker, mtk_usb_extcon_detect_cable [extcon_mtk workqueue events_freezable_power_: flags=0x84 pwq 10: cpus=5 node=0 flags=0x0 nice=0 active=2/256 refcnt=3 in-flight: 19077:disk_events_workfn pending: thermal_zone_device_check workqueue mm_percpu_wq: flags=0x8 pwq 0: cpus=0 node=0 flags=0x0 nice=0 active=1/256 refcnt=2 pending: vmstat_update workqueue writeback: flags=0x4a pwq 12: cpus=0-5 flags=0x4 nice=0 active=3/256 refcnt=5 in-flight: 6748:wb_workfn, 11170:wb_workfn, 3306:wb_workfn workqueue usb_hub_wq: flags=0x4 pwq 0: cpus=0 node=0 flags=0x0 nice=0 active=2/256 refcnt=3 in-flight: 32634:hub_event pending: hub_event workqueue dm_bufio_cache: flags=0x8 pwq 0: cpus=0 node=0 flags=0x0 nice=0 active=1/256 refcnt=2 pending: work_fn workqueue sock_diag_events: flags=0x0 pwq 10: cpus=5 node=0 flags=0x0 nice=0 active=1/256 refcnt=2 in-flight: 21204:sock_diag_broadcast_destroy_work pwq 8: cpus=4 node=0 flags=0x0 nice=0 active=1/256 refcnt=2 in-flight: 18293:sock_diag_broadcast_destroy_work pwq 6: cpus=3 node=0 flags=0x0 nice=0 active=2/256 refcnt=3 in-flight: 20909:sock_diag_broadcast_destroy_work, 20908:sock_diag_broadcast_destroy_work workqueue extcon_usb: flags=0xe000a pwq 12: cpus=0-5 flags=0x4 nice=0 active=1/1 refcnt=3 in-flight: 14777:mtk_usb_extcon_update_role [extcon_mtk_usb] workqueue mfd_wq: flags=0x6000e pwq 12: cpus=0-5 flags=0x4 nice=0 active=1/1 refcnt=4 in-flight: 11127:mfd_irq_responce_work [changan_mfd] inactive: mfd_irq_responce_work [changan_mfd] pool 0: cpus=0 node=0 flags=0x0 nice=0 hung=31s workers=5 idle: 16783 20407 19600
最新发布
08-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值