问题描述:有一个定时服务,如每5秒执行一次服务
在这个服务里,要使用多个线程同时启动
如:int servicenum = 5;同时启用5个线程
整个服务不能多于5线程,
如:第一次服务 启用了5个线程,到第二次启用服务时,如果这5个线程只有2个空闲,那么只启用空闲的2个线程
第3次再去查看这5个线程中有哪些空闲。开始是想的写一个类去做定时服务,但是每次new一个实例,我想太没效率,就想到每次服务启用多个服务。但这怎么写呢?写了个线程,主线程,指定要new出的线程数,然后循环new出线程,例子:
public  static void main(String [] args){
int j = 9;
List<Object> list = new ArrayList<Object>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
list.add("9");

ThreadOne t ;
for(int i=0;i<j;i++)
{
t =  new ThreadOne(list.get(i).toString());
t.start();
}
}但这样怎么显示我的功能呢?怎么监听线程状态啊,请大家给点方法。····

解决方案 »

  1.   

    java Timer + 线程池实现 
    主线程判断线程池中的状态!
      

  2.   

    你是要写一个线程池?还是用一下而已?看下ThreadGroup
      

  3.   

    ThreadGroup还有人用?
    线程池现在的Java里又不是没有。看看ExecutorService吧。
      

  4.   

    让你学习点timer和timertask的知识吧 嘿嘿1.Timer和TimerTask介绍
    Timer是一种定时器工具,用来在一个后台线程计划执行指定任务。它可以计划执行一个任务一次或反复多次。
    TimerTask一个抽象类,它的子类代表一个可以被Timer计划的任务。2.制定执行计划方法介绍
    1)public void schedule(TimerTask task,Date time)
    Task被安排在Timer指定的时间执行,如果时间为过去时则任务立刻执行。且该任务只执行一次。
    2)public void schedule(TimerTask task, Date firstTime, long period) 
    Task被安排在Timer指定的时间执行,执行后将每隔period(毫秒)反复执行。由于规定的时间间隔并不能保证与时钟精准的同步,所以该方法最适合从短期看保持频率准确的地方。
    3)public void schedule(TimerTask task, long delay)
    Task被安排在delay(毫秒)指定的时间后执行。且该任务只执行一次。
    4)public void schedule(TimerTask task,long delay, long period)
    Task被安排在delay(毫秒)指定的时间后执行。执行后将每隔period(毫秒)反复执行。
    5)public void scheduleAtFixedRate(TimerTask task,Date firstTime, long period)
    Task被安排在firstTime指定的时间执行。执行后将每隔period(毫秒)反复执行。每一次重复的时间是和第一次执行而不是和前一次执行有关。因此执行的总速度是固定的。
    6)public void scheduleAtFixedRate(TimerTask task,long delay,long period)
    Task被安排在delay(毫秒)指定的时间后执行。执行后将每隔period(毫秒)反复执行。每一次重复的时间是和第一次执行而不是和前一次执行有关。因此执行的总速度是固定的。
    2),4),5),6)四个方法是需要注意的。计划反复执行的任务时,如果你注重任务执行的平滑度,那么请使用schedule方法,如果你在乎的是任务的执行频度那么使用scheduleAtFixedRate方法。3.用Timer线程实现和计划执行一个任务的基础步骤:
    1)实现自定义的TimerTask的子类,run方法包含要执行的任务代码。
    2)实例化Timer类,创建计时器后台线程。 
    3)实例化任务对象。 
    4)制定执行计划。
    应用:
    //实现自定义的TimerTask的子类public class TimerTaskTest extends TimerTask{
    public void run() {
    // 需要定时执行的代码……
    }
    }
    ……
    private java.util.Timer timer; 
    private java.util.TimerTask timerTask;
    ……
    Timer timer = new Timer(true); 
    TimerTask
    timerTask = new TimerTaskTest ();
    timer.schedule(timerTask, 0, 5*60*1000);// 间隔5分钟执行一次Task
    ……
      

  5.   

    嗯,谢谢,知道怎么定时了。
    但还是不知道怎么在没一个Timer线程中启用另外5个线程,和监听。ExecutorService也不好用样。
      

  6.   

    谁能给我贴点ExecutorService线程池的代码啊?
    O(∩_∩)O谢谢了。
    急用啊,
    我有个线程了,
     每5秒执行1次时间服务,要在每个时间的run里实例5个线程。线程里执行业务
    最大5个线程。怎么用线程池控制啊。
      

  7.   

    楼主,服务和任务的概念很模糊啊。
    看了一边,没太看懂是什么意思。多个线程执行什么任务 ?  是多线程协作一个任务,还是分别执行不同的任务 ?
    还是
    要写一个Monitor线程,每5秒检测一次,保证5线程的线程池里,每个线程都要分配到任务去做 ?
      

  8.   

    这样的,
    一个定时类,每5秒执行1次,定时类run方法里,同时实例化5个线程类。
    线程类里就是要执行的服务了。
    需要保证的是,当第10秒第2次执行(以及以后,15秒,20秒··)都要保证只有5个线程。
    用线程池能实现这个功能吧,但不知道怎么用。
      

  9.   

    简单的按楼主的意思写了一个,感觉很怪异。一会我按自己的意思写一个。
    public class ThutsTimer extends TimerTask{ private List<Thread> threads = Collections.synchronizedList(new ArrayList<Thread>(5));
    private volatile boolean hasNotInit = true;

    private void init() {
    //实例化5个线程。
    Thread t1 = new Thread();Thread t2 = new Thread();
    Thread t3 = new Thread();Thread t4 = new Thread();
    Thread t5 = new Thread();
    threads.add(t1);threads.add(t2);threads.add(t3);
    threads.add(t4);threads.add(t5);
    } public void run() {
    if(hasNotInit){
    init();
    }
    synchronized (threads) {
    for(Thread t : threads){
    if(Thread.State.TERMINATED==t.getState() || Thread.State.NEW==t.getState()){
    t.start();
    }
    }
    }
    }
    public static void main(String[] args) {
    final long delay = 5*60*1000;
    java.util.Timer timer = new java.util.Timer();
    timer.schedule(new ThutsTimer(), delay);
    }}
      

  10.   

    public class Monitor implements Runnable { private final long Cycle = 5*60*1000;//5分钟为一周期。
    private List<Thread> threads = Collections.synchronizedList(new ArrayList<Thread>(5));
    private volatile boolean running = false;
    private Thread instance = null;

    public Monitor() {
    instance = new Thread(this);
    initTasks();
    } private void initTasks() {
    //实例化5个线程。
    Thread t1 = new Thread();Thread t2 = new Thread();
    Thread t3 = new Thread();Thread t4 = new Thread();
    Thread t5 = new Thread();
    //初始化线程列表。
    threads.add(t1);threads.add(t2);threads.add(t3);
    threads.add(t4);threads.add(t5);
    } public void run() {
    while(running){
    //确保有5个线程在运行
    for(Thread t : threads){
    if(Thread.State.TERMINATED==t.getState() || Thread.State.NEW==t.getState()){
    t.start();
    }
    }
    //延时
    try {
    Thread.sleep(Cycle);
    } catch (InterruptedException e) {
    }
    }
    } public synchronized void startup(){
    if(!running){
    running=true;
    instance.start();
    }
    }

    public synchronized void shutdown(){
    if(running){
    running=false;
    instance.interrupt();
    try {
    instance.wait();
    } catch (InterruptedException e) {
    }
    }
    }

    public static void main(String[] args) {
    Monitor m = new Monitor();
    m.startup();
    }}
      

  11.   

    O(∩_∩)O谢谢,知道方法了。
    但现在这里我想有问题吧。
    当第2次运行,也就是第10秒时(5秒运行一次),
    线程的状态为new时,也会去执行t.star();这样就会出现java.lang.IllegalThreadStateException异常。
      

  12.   

    preferme:这样能控制整个程序执行起来,一直始终都是5个线程吗?我在这5个线程分别传入,a,b,c,d,e,当传a时,我让它睡15秒,结果是不止5个线程在同时执行---第2次又有5个线程被执行了,加上第1次的a就6个了。
      

  13.   


    package com.yangtianb.NEWTEST;
    import java.util.TimerTask;import com.yangtianb.ThreadPool.ThreadPool;public class ThutsTimer extends TimerTask{
    private ThreadPool c;
    public ThreadPool getC() {
    return c;
    } public void setC(ThreadPool c) {
    this.c = c;
    }
    ThutsTimer(ThreadPool c){
    this.c = c;
    }
     public void run() {
     System.out.println("-------------------");  
           c.server();
           }    public static void main(String[] args) {
            final long delay = 3*1000;
            java.util.Timer timer = new java.util.Timer();
            ThreadPool c = new ThreadPool();
            ThutsTimer timermain = new ThutsTimer(c);
        
            timer.schedule(timermain,0,delay);
        }
    }
    package com.yangtianb.ThreadPool;import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;public class ThreadPool {
    private ExecutorService exe=null;//线程池
     private static final int POOL_SIZE=4;//线程池的容量
     
     public ThreadPool()
     {
      exe=Executors.newFixedThreadPool(POOL_SIZE);//创建线程池
      System.out.println("the server is ready...");
     }
     
     public  void server()
     {
      int i=0;
      while(i<8)
      {
       exe.execute(new Worker(i));//运行线程池
       i++;
      }
     }
     
     class Worker extends Thread //工作线程,线程要完成的工作在此类中实现
     { 
      int id;
      Worker(int id)
      {
       this.id=id;
      }
      public void run() {
       if(id==0){
    try {
    this.sleep(4000);
    System.out.println("task 我是"+id+":start");//具体要做的事
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
       }else{
       try {
    this.sleep(6000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println("task "+id+":start");//具体要做的事
       }
      }
     } 
    }线程池是这样用的吧。能够解决