📄 worker.java
字号:
/*
* Worker.java
*
* Created on January 14, 2006, 3:55 PM
*/
package com.dtw.midp.util;
import java.util.Vector;
/**
* <code>Worker</code> is a class that can run tasks inside a separate,
* dedicated thread.
* The new thread is created and run inside <code>Worker</code>'s
* constructor. You can request that a task be run by
* passing a <code>WorkerTask</code> to the <code>queue()</code> method.
*
* @author Jonathan Knudsen
* @used by psaingtong
*
*/
public class Worker implements Runnable{
private boolean trucking;
private Vector queue;
private WorkerListener tWorkerListener;
private boolean tCancel;
/**
* Creates a new <code>Worker</code> and kicks off its thread.
*
* @param pd a <code>ProgressDisplay</code> implementation
* that will show an indicator while this
* <code>Worker</code> is performing a task
*/
public Worker() {
trucking = true;
queue = new Vector();
tCancel = false;
Thread t = new Thread(this);
t.start();
}
/**
* Assigns a listener object.
*/
public void setWorkerListener(WorkerListener listener){
tWorkerListener = listener;
}
/**
* Queues a <code>WorkerTask</code> for execution. The
* task executes immediately if the queue was empty.
*/
public void queue(WorkerTask r) {
// Add it to the queue.
queue.addElement(r);
// Unstick run(). Only call this if we've just added
// a task to an empty queue, which means that run()
// is waiting to be woken up.
if (queue.size() == 1)
synchronized(this) { notify(); }
}
/**
* This method is called by the constructor. Normally
* you will not need to call this method yourself.
*/
public synchronized void run() {
while (trucking) {
// If there are no more tasks in the queue,
// go to sleep.
if (queue.size() == 0) {
try { wait(); }
catch (InterruptedException ie) {}
}
// If we're still running.
if (trucking) {
WorkerTask r = (WorkerTask)queue.elementAt(0);
try {
r.run();
tWorkerListener.finished(r);
}
catch (Exception e) {
if (tCancel == false)
tWorkerListener.exception(r, e);
tCancel = false;
}
// Whatever happened, remove the task from the
// queue.
queue.removeElementAt(0);
}
}
}
/**
* Cancels the currently running task.
*/
public void cancel() {
WorkerTask task = null;
try { task = (WorkerTask)queue.elementAt(0); }
catch (ArrayIndexOutOfBoundsException aioobe) {}
if (task == null) return;
tCancel = true;
task.cancel();
}
/**
* Shuts down this <code>Worker</code>.
*/
public void stop() {
trucking = false;
notify();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -