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个新的线程,这样子做存在效率问题吗?
线程的生命周期什么时候结束呢,旧的线程来得及释放回收吗.
有没有什么好方法优化一下.

解决方案 »

  1.   

    用线程池,ScheduledExecutorService
      

  2.   

    使用Timer每1秒钟用5个线程做某事.你确定在这一秒中 每个线程都是运行中的CPU执行时间片是争用的 每次都new肯定是不行的
      

  3.   

    又是你,呵呵,我的代码都够简化了,你也写个简单的demo来给我呀
      

  4.   

    回去又写了2个 不知道哪个好 public class test2 {
    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();
    }
    }达人帮我看下咯