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);
}
}
}