import java.util.Timer;
import java.util.TimerTask;public class myTimer {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() { for (int i = 0; i < 5; i++) { thread thread = new thread();
thread.start(); }
}
}, 0, 1000);
}}class thread extends Thread {
public void run() {
System.out.println(currentThread().getName() + " is running");
}
}使用Timer每1秒钟用5个线程做某事.但是发现,每次都是new5个新的线程,这样子做存在效率问题吗?
线程的生命周期什么时候结束呢,旧的线程来得及释放回收吗.
有没有什么好方法优化一下.
import java.util.TimerTask;public class myTimer {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() { for (int i = 0; i < 5; i++) { thread thread = new thread();
thread.start(); }
}
}, 0, 1000);
}}class thread extends Thread {
public void run() {
System.out.println(currentThread().getName() + " is running");
}
}使用Timer每1秒钟用5个线程做某事.但是发现,每次都是new5个新的线程,这样子做存在效率问题吗?
线程的生命周期什么时候结束呢,旧的线程来得及释放回收吗.
有没有什么好方法优化一下.
public static void main(String[] args) { for (int i = 0; i < 5; i++) {
thread thread = new thread();
thread.start();
} }}class thread extends Thread {
public void run() {
while (true) {
System.out.println(currentThread().getName() + " is running");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
------------------------分割线-----------------------
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;public class test3 {
public ScheduledExecutorService scheduExec = Executors
.newScheduledThreadPool(5); // 添加新任务
public void addOneTask() {
Runnable task = new Runnable() {
public void run() {
System.out.println("welcome to china");
}
};
scheduExec.scheduleWithFixedDelay(task, 0, 1000, TimeUnit.MILLISECONDS);
} public static void main(String[] args) throws Exception {
test3 test = new test3();
for (int i = 0; i < 5; i++) {
test.addOneTask();
} // test.cancelTask();
} private void cancelTask() {
// scheduExec.shutdown();
scheduExec.shutdownNow();
}
}达人帮我看下咯