模拟线程池,处理异步任务

public class Task implements Runnable {

	private String name = "default";
	private boolean available = false;
	private Queue<Task> queue;
	
	public Task(Queue queue) {
		System.out.println("entry task.");
		this.queue = queue;
	}
	
	// 主线程调用后,唤醒工作线程,将参数传递给工作线程处理。为了接受另一个请求
	public synchronized void assign(String s) {
		System.out.println("task assined...");
		while (available) {
			try {
				wait();
			} catch (Exception e) {

			}
		}
		this.name = s;
		available = true;
		notifyAll();
	}

	@Override
	public void run() {
		System.out.println("run...");
		while (true) {
			// step 1.
			String myName = await();
			// step 2.
			process(myName);
			// step 3. recycle();
			queue.offer(this);
		}

	}

	public synchronized String await() {

		System.out.println("waiting...");
		while (!available) {
			try {
				wait();
			} catch (Exception e) {

			}
		}
		available = false; // 子线程设置,目的:1.使assign()和处理 异步化 。2.使assign()可以及时分配请求
		notifyAll();

		String tmp = name;
		return tmp;
	}

	public synchronized void process(String name) {
		System.out.println("processing...");
		for (int i = 0; i < 10000000; ++i) {
			;
		}
		System.out.println(name);
	}
	
	public void start() {
		Thread thread = new Thread(this);
		thread.start();
	}

}

public class Main {

	static Queue<Task> queue = new LinkedBlockingQueue<Task>();

	public static void init() {
		for (int i = 0; i < 10; ++i) {
			Task t = new Task(queue);
			t.start();
			queue.offer(t);
		}
		System.out.println("init..." + queue.size());
	}

	public static void main(String args[]) {

		init();

		for (int i = 0; true; ++i) {
			String tmp = "" + i;
			// System.out.println(tmp);
			Task cur = queue.poll();
			if (cur == null)
				continue;
			else
				cur.assign(tmp);
		}

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值