代码如下:
public class TQueue
{
/**
*
*
*
*/
class ThreadPool extends Thread
{
/**
* 从任务队列获取任务并执行.
*/
public void run()
{
while(true)
{
Runnable runnable;
try
{
{
runnable = null;
synchronized(TQueue.this)//?这里有问题?说没有获得锁,不知道为什么
{
runnable = getWork();
if(runnable != null)
{
runnable.run();
continue;
}
try
{
wait(0x186a0L);//100秒
}
catch(Throwable throwable1) {
}
}
continue;
}
}
catch(Throwable throwable) { }
}
}
/**
*
*
*/
ThreadPool()
{
super();
}
} /**
* 构造一个线程任务队列和含有指定个数线程的线程池.
* @param i
*/
public TQueue(int i)
{
workList = new LinkedList();
for(int j = 0; j < i; j++)
(new ThreadPool()).start(); }
/**
* 将指定的任务添加到线程任务队列中.
* @param runnable 待加入的任务
*/
public synchronized void addWork(Runnable runnable)
{
workList.add(runnable);
notify();
}
/**
* 获取待执行的任务.
* @return Runnable 返回执行任务的线程
*/
public synchronized Runnable getWork()
{
if(workList.size() == 0)
{
return null;
} else
{
Runnable runnable = (Runnable)workList.remove(0);
return runnable;
}
}
/**
* 测试函数
*/
public static void main(String args[])
{
TQueue tqueue = new TQueue(2);
try
{
do
{
int i = System.in.read();
tqueue.addWork(new Work());
} while(true);
}
catch(Throwable throwable)
{
throwable.printStackTrace();
}
}
protected LinkedList workLIst;
}
class Work
implements Runnable
{ Work()
{
}
/**
* 具体运行的任务.
*/
public void run()
{
System.out.println(toString() + " run start");
try
{
Thread.sleep(3000L);
}
catch(Exception exception) { }
System.out.println(toString() + " run end");
}
}
public class TQueue
{
/**
*
*
*
*/
class ThreadPool extends Thread
{
/**
* 从任务队列获取任务并执行.
*/
public void run()
{
while(true)
{
Runnable runnable;
try
{
{
runnable = null;
synchronized(TQueue.this)//?这里有问题?说没有获得锁,不知道为什么
{
runnable = getWork();
if(runnable != null)
{
runnable.run();
continue;
}
try
{
wait(0x186a0L);//100秒
}
catch(Throwable throwable1) {
}
}
continue;
}
}
catch(Throwable throwable) { }
}
}
/**
*
*
*/
ThreadPool()
{
super();
}
} /**
* 构造一个线程任务队列和含有指定个数线程的线程池.
* @param i
*/
public TQueue(int i)
{
workList = new LinkedList();
for(int j = 0; j < i; j++)
(new ThreadPool()).start(); }
/**
* 将指定的任务添加到线程任务队列中.
* @param runnable 待加入的任务
*/
public synchronized void addWork(Runnable runnable)
{
workList.add(runnable);
notify();
}
/**
* 获取待执行的任务.
* @return Runnable 返回执行任务的线程
*/
public synchronized Runnable getWork()
{
if(workList.size() == 0)
{
return null;
} else
{
Runnable runnable = (Runnable)workList.remove(0);
return runnable;
}
}
/**
* 测试函数
*/
public static void main(String args[])
{
TQueue tqueue = new TQueue(2);
try
{
do
{
int i = System.in.read();
tqueue.addWork(new Work());
} while(true);
}
catch(Throwable throwable)
{
throwable.printStackTrace();
}
}
protected LinkedList workLIst;
}
class Work
implements Runnable
{ Work()
{
}
/**
* 具体运行的任务.
*/
public void run()
{
System.out.println(toString() + " run start");
try
{
Thread.sleep(3000L);
}
catch(Exception exception) { }
System.out.println(toString() + " run end");
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货