本帖最后由 lycongzsu 于 2010-07-17 18:29:43 编辑

解决方案 »

  1.   

    其实我是在香港在读的一名计算机博士(惭愧),上面那个问题源自我现在写的一篇论文(关于研究在一个庞大的图里面,怎样去判断任意2点之间的相关性)。上面那个work函数 是关于 找2点之间经过的所有路径的,所以有递归东西在里面,但是由于我的那个图太大(大概有1万多个点,7万多条link)。
      

  2.   

    上面那个work函数 是关于 找2点之间经过的所有路径的,所以有递归东西在里面,但是由于我的那个图太大(大概有1万多个点,7万多条link), 执行的时间比较非常的长,所以进行时间上的限制。
      

  3.   

    java.util.concurrent 包 中的 Future等类提供对超时的处理
      

  4.   

    我有个死一点的方法可以试一试:
    work函数中实现一个获取时间的方法:System.currentTimeMillis(),由于work是递归的,时间赋值给一个全局变量即可,超时就退出咯。想法是这样,不知道有错不? 
      

  5.   


    你的那个方法 我大概算过了用时,基本上要几分钟才能看到一个input的最终计算结果,但我那里有接近2万个input,要算完全部结果的话估计比较杯具
      

  6.   


    速度应该就是你算法的优化问题了吧。System.currentTimeMillis()肯定是可以控制超时退出的,时间值再设小一点。这个得出的时间单位是毫秒。
      

  7.   


    //算法工作线程
    class WorkTask implements Runnable{

    public void run(){
    while(true){
    //把下面的控制语句加到算法中最频繁的循环逻辑中
    if(Thread.currentThread().interrupted()){
    System.out.println("时间到");
    //如果当前线程被置位了,立即跳出工作逻辑,回到开始的地方重新进行
    }
    }
    }
    }//时间控制线程
    class TimeTask implements Runnable{

    private Thread work=null;

    TimeTask(Thread w){
    this.work=w;
    }

    public void run(){
    int count=1;
    while(true){
    System.out.println(count+"s");
    try{
    //当前线程休息1s
    Thread.sleep(1000); 
    }catch(InterruptedException e){
    e.printStackTrace();
    }
    if(count==10){
    //当时间达到10s的时候,置工作线程的中断状态位,改变工作线程的运行逻辑
    work.interrupt(); 
     //重新计时
    count=0;
    }
    count++;
    }
    }
    }
    //测试
    public class Test{ public static void main(String[] arg) throws InterruptedException
    {
    Thread word=new Thread(new WorkTask());
    Thread time=new Thread(new TimeTask(word));
    word.start();
    time.start();

    }
    不知道上面的代码能不能解决你的问题。可以考虑使用interrupt()来改变算法线程的运行逻辑。
      

  8.   

    示例代码
    ExecutorService service = Executors.newCachedThreadPool();final Runnable doThing = new Runnable() {
    public void run() { work(input); }
        };Future f = service.submit(doThing);
    scheduler.schedule(new Runnable() {
    public void run() { 
        if(f.isDone()){
    ... // do something
        } else{
    f.cancel(true); 
        }
    }
        }, 60, TimeUnit.SECONDS); // 60s 未完成即放弃
      

  9.   

    不知道哦可以不
    但是不能解决根本问题
    根本问题在于你的算法的优化
    我们一个同事把一个寻路的算法从最开始的十几分钟最后优化到5秒内/**
     * desc:
     *     XXX<br>
     * ----------------------------------------------------------------------------
     * ver.            date           who           what
     * ----------------------------------------------------------------------------
     * 0.0.1           2010-7-17      leisore       add
     * ----------------------------------------------------------------------------
     */
    package cn.leisore.daily._2010_07_17;import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;import cn.leisore.daily._2010_07_17.WithExecutor.ChildThead;/**
     * TimeoutFuture
     * 
     * @author leisore
     * @since version 0.0.1
     */
    public class TimeoutFuture {    /**
         * @param args
         */
        public static void main(String[] args) {
            ExecutorService pool = Executors.newFixedThreadPool(3);        List<Callable<Boolean>> list = new ArrayList<Callable<Boolean>>();
            for (String input : new String[] { "leisore1", "leisore2", "leisore3" }) {
                list.add(new Work(input));
            }        try {
                List<Future<Boolean>> invokeAll = pool.invokeAll(list);
                for (Future<Boolean> f : invokeAll) {
                    try {
                        f.get(100, TimeUnit.MILLISECONDS);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    } catch (TimeoutException e) {
                        e.printStackTrace();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                pool.shutdown();
            }        System.out.println("Main finished");
        }    static class Work implements Callable<Boolean> {
            private String name = null;        public Work(String name) {
                this.name = name;
            }        public Boolean call() throws Exception {
                Thread.sleep(Math.abs(new Random().nextInt(10000)));
                System.out.println(name);
                return true;
            }
        }
    }
      

  10.   

       线程方面属于入门级
         刚开始还以为是spring的定时器呢
       友情了 
      

  11.   

    这个可以用定时器来做,work用另一个线程,主线程用Timer检查work是否在执行,超时就终止掉。
      

  12.   

    14楼,你的这个代码不对啊,不能实现我的那个功能: 对每个input的处理只能不超过设定时间(30秒),否则继续处理下个input但你的这行代码不是我所要的那个功能
    List<Future<Boolean>> invokeAll = pool.invokeAll(list);
      

  13.   

    高强度计算的话,我还是建议用底层的 API 实现。        ExecutorService es = Executors.newCachedThreadPool();
            try {
                for (final String str : arr) {
                    Future<?> f = es.submit(new Runnable() {                    public void run() {
                            work(str);
                        }
                    });
                    try {
                        f.get(30, TimeUnit.SECONDS);
                    } catch (TimeoutException ex) {
                        //f.cancel(true);
                    }
                }
            } finally {
                es.shutdown();
            }
      

  14.   

    我总结一下我上面问题解决了的代码吧:
    class Work implements Callable<Result> {
       private String input;
        public Work(String input){
    this.input = input;
    }public Result call() throws Exception{
        deal(input);  //具体的处理input的逻辑代码
    }}class TestProgram{
     public static void main(String[] args){
        List<String> inputs = ;  //具体的一系列input
        ExecutorService pool = Executors.newCachedThreadPool();
    List<Callable<Result>> list = new ArrayList<Callable<Result>>();for(String input: inputs){
      Work work = new Work(input);
      list.add(work);
    }try{
    for(Callable<Result> task : list){
    Future<Result> f = pool.submit(task);
    try{
      Result result = f.get(30, TimeUnit.SECONDS);
     
    if(f.isDone()){
      /*deal with the result */
    }
    }
    catch (InterruptedException e) {
    e.printStackTrace();
    } catch (ExecutionException e) {
    e.printStackTrace();
    } catch (TimeoutException e) {
    //e.printStackTrace();
    //continue;
    f.cancel(true);
    }
    }
    } finally{
     pool.shutdown();
    }System.out.println("Finished");
        }}