日期:2014-05-20  浏览次数:20740 次

如何把一段创建新线程的代码封装成一个类,然后另一个类中引用?如何引用?
package com.example.demo;
  
import java.util.concurrent.Callable;  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
import java.util.concurrent.Future;  
  
public class  trdSoap {  
  
    public static void main(String[] args) {  
     final String  rtnString = null ;
    
        ExecutorService executor = Executors.newFixedThreadPool(3);  
        try {  

            final Future<String> future2 = executor.submit(new Callable<String>() {  
                @Override  
                public String call() throws Exception {               
                    try {  
                        while (true) {  
                            System.out.println("demo");
                         Thread.sleep(50);                             
                        }  
                    } catch (InterruptedException e) {  
                    }  
                    return rtnString;  
                }  
            });  
              
        } catch (Exception e) {  
        }  

        executor.shutdownNow();  
    }  
    
    
    
}  
------解决方案--------------------

    public abstract class HandlersBase
    {
        protected bool isBusy = false;
        protected bool isFinished = true;
        protected Task task;
        public HandlersBase(string showStr,CancellationToken token)
        {
            task = Task.Factory.StartNew(Handler,token,token,TaskCreationOptions.LongRunning,TaskScheduler.Default);
            MessageModel.Message(string.Format("{0} 启动完成!", showStr));
        }

        public bool IsHandlersBusy()
        {
            return isBusy;
        }

        public abstract bool IsHandlersFinished();
        public abstract void Handler(object token);
    }

 public class TranslatorHandler : HandlersBase
    {
        public TranslatorHandler(int i,CancellationToken token)
            : base("翻译线程" + i.ToString(),token)
        { }

        public override void Handler(object token)
        {
            while (!((CancellationToken)token).IsCancellationRequested)