📄 threadpoolworker.java
字号:
package com.hxyh.sanny.mms.cmcc.base.thread;
public class ThreadPoolWorker
{
private static int nextWorkerID = 0;
private long nTimeout = 0;
private int completedWorks = 0;
private ObjectFIFO idleWorkers;
private int workerID;
private ObjectFIFO handoffBox;
private Thread internalThread;
private volatile boolean noStopRequested;
private int priority = -1;
public ThreadPoolWorker(ObjectFIFO idleWorkers)
{
this.idleWorkers = idleWorkers;
workerID = getNextWorkerID();
handoffBox = new ObjectFIFO(1);
noStopRequested = true;
init();
}
public ThreadPoolWorker(ObjectFIFO idleWorkers, int priority)
{
this.idleWorkers = idleWorkers;
workerID = getNextWorkerID();
handoffBox = new ObjectFIFO(1);
noStopRequested = true;
this.priority = priority;
init();
}
private void init()
{
Runnable r = new Runnable() {
public void run()
{
try
{
runWork();
}
catch(Exception x)
{
x.printStackTrace();
}
}
};
internalThread = new Thread(r);
if (priority > 0)
internalThread.setPriority(priority);
internalThread.start();
}
public void setTimeout(long l)
{
this.nTimeout = l;
}
public static synchronized int getNextWorkerID()
{
int id = nextWorkerID;
nextWorkerID++;
return id;
}
public void process(Runnable target)
throws InterruptedException
{
handoffBox.add(target);
}
private void runWork()
{
while(noStopRequested)
try
{
//System.out.println("workerID=" + workerID +", ready for work");
// Worker is ready work. This will never block
// because the idleWorker FIFO queue has
// enough capacity for all the workers.
idleWorkers.add(this);
// wait here until the server adds a request
Runnable r = (Runnable)handoffBox.remove();
//System.out.println("workerID=" + workerID +", starting execution of new Runnable: " + r);
if (nTimeout > 0)
{
runIt(r,nTimeout);
}
else
{
runIt(r);
}
}
catch(InterruptedException x)
{
Thread.currentThread().interrupt();
}
finally
{
completedWorks++;
}
}
private void runIt(Runnable r)
{
try
{
r.run();
}
catch(Exception runex)
{
runex.printStackTrace();
}
finally
{
Thread.interrupted();
}
}
private void runIt(Runnable r,long msTimeout)
{
try
{
ThreadTimer.getInstance().schedule(new ThreadTimerTask(this,this.getCompletedWorks()),msTimeout);
r.run();
}
catch(Exception runex)
{
runex.printStackTrace();
}
finally
{
Thread.interrupted();
}
}
public void stopRequest()
{
noStopRequested = false;
internalThread.interrupt();
try
{
Thread.sleep(250L);
}
catch(InterruptedException interruptedexception) { }
}
public void restart()
{
stopRequest();
noStopRequested = true;
init();
}
public boolean isAlive()
{
return internalThread.isAlive();
}
public int getCompletedWorks()
{
return this.completedWorks;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -