java中起一个线程池 每秒开启3个线程 每个线程睡眠2秒 2秒之后关闭线程 !!!!

2025-04-06 00:37:55
推荐回答(1个)
回答1:

class mythread extends Thread{

private String id;

/**
 * 
 */
public mythread(String id) {
// TODO Auto-generated constructor stub
this.id=id;
}

@Override
public void run() {
System.out.println(id+"\t正在执行......  Time:"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
try {
this.sleep(2*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(id+"\t关闭......  Time:"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
}

}
public static void main(String[] args) throws Exception {
ThreadPoolExecutor tpe=(ThreadPoolExecutor) Executors.newCachedThreadPool();
while(true){
for (int i = 0; i < 3; i++) {
String id=UUID.nameUUIDFromBytes((i+"").getBytes()).toString();
tpe.execute(new mythread(id));
}
System.out.println("当前线程数为:"+tpe.getPoolSize());
Thread.sleep(1000);
}

}