我需要做的是使用大小为3的FixedThreadPool,然后用它来打印ThreadName,然后让它在指定的时间间隔内随机 hibernate 一段时间并打印当它完成时它是醒着的。我需要逐个线程执行此操作,但我的输出来自所有 3 个线程。
期望的输出: pool-1-thread-1 进入休眠状态,持续 800 毫秒到 1000 毫秒之间的随机时间间隔
pool-1-thread-1 已 hibernate
pool-1-thread-2 进入 hibernate 状态,持续 800 毫秒到 1000 毫秒之间的随机时间间隔
pool-1-thread-2 已 hibernate
pool-1-thread-3 进入 hibernate 状态,持续 800 毫秒到 1000 毫秒之间的随机时间间隔
pool-1-thread-3 完成 sleep
我只需要使用FixedThreadPool
import java.util.Random;
import java.util.concurrent.*;
class Sleep implements Runnable
{
public void run()
{
Random ran = new Random();
int randomnumber = ran.nextInt(1000-800+1)+800;
System.out.print(Thread.currentThread().getName()+" ");
System.out.println("Going to sleep for random amount of time interval between 800 ms and 1000ms");
try
{
Thread.sleep(randomnumber);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" done sleeping");
Thread.yield();
}
}
public class Ch6Ex3
{
public static void main(String[] args)
{
ExecutorService exe = Executors.newFixedThreadPool(3);
for(int i=0;i<3;i++)
{
exe.execute(new Sleep());
}
exe.shutdown();
}
}
最佳答案
创建只有 1 个线程的线程池。如果您使用 3 个线程,则最多可以同时运行 3 个可运行线程,但这不是您想要的。所以使用:
ExecutorService exe = Executors.newFixedThreadPool(1);
实际上更好的选择是使用 newSingleThreadExecutor
因为它明确表明它在任何给定时间仅运行 1 个可运行程序:
ExecutorService exe = Executors.newSingleThreadExecutor();
两种方法在内部都会创建 ThreadPoolExecutor
有 1 个线程,因此它们之间仅在命名上没有实际区别。
关于java - 固定线程池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14335410/