java 스 레 드 탱크 순환 반복 list 정의

10109 단어 Java
java 스 레 드 탱크 순환 반복 list 정의
만약 list 에 1000 개의 데이터 가 있다 면, 당신 은 순간 에 천 개의 라인 이 생 겼 을 뿐만 아니 라, 코드 를 쓰기 위해 동기 화 문 제 를 주의해 야 합 니 다.당신 의 이 코드 의 가장 심각 한 문 제 는 하위 스 레 드 처리 결과 당신 의 메 인 스 레 드 가 매우 번 거 로 워 야 한 다 는 것 입 니 다. 이 점 은 실제 프로젝트 응용 에서 매우 중요 합 니 다!
내 가 너 에 게 보 낸 그 코드 는 내 가 사용 할 수 있 는 것 을 측정 한 적 이 있다. 대충 생각 을 바 꾸 는 것 은:
'한 번 훑 어 보 는 데 15 초 정도 걸 립 니 다' 라 는 일 을 하나의 클래스 에 기록 합 니 다. 클래스 는 Callable 인 터 페 이 스 를 실현 합 니 다. 이것 을 우 리 는 하나의 임무 라 고 부 릅 니 다.
그리고 당신 은 List 가 있 지 않 습 니까? 이 list 를 옮 겨 다 니 며 퀘 스 트 배열 을 구축 합 니 다 ConcurrentExcutor 대상 을 만 들 고 배열 의 작업 을 수행 합 니 다 다음은 제 프로젝트 의 호출 코드 입 니 다. 참고 하 십시오. (ProcessNumTask 는 바로 Callable 을 실현 하 는 작업 입 니 다)
ProcessNumTask[] tasks = new ProcessNumTask[tempList.size()];
        for(int i=0; i ce = new ConcurrentExcutor(tasks, 5, result);
        ce.excute();
import java.util.List;
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;
 
/**
 *      
 *        (  ):
 *       ,  150         ,     ,        20 (   ),       8   ,       
 *
 * @param    T     Callable                     bean
 */
public class ConcurrentExcutor
{
    /**   ,       */
    private Callable[] tasks;
     
    /**   ,             */
    private int numb;
     
    /**   ,      ,      ,  T   Callable     T */
    private List result;
     
    /**
     *     
     */
    public ConcurrentExcutor()
    {
        super();
    }
 
    /**
     *                 
     * @param tasks
     * @param numb
     */
    public ConcurrentExcutor(Callable[] tasks, int numb)
    {
        super();
        this.tasks = tasks;
        this.numb = numb;
    }
 
    /**
     *              
     * @param tasks
     * @param numb
     * @param result
     */
    public ConcurrentExcutor(Callable[] tasks, int numb, List result)
    {
        super();
        this.tasks = tasks;
        this.numb = numb;
        this.result = result;
    }
 
    public void excute()
    {
        //     
        if(tasks == null || numb < 1)
        {
            return;
        }
         
        //        
        int num = tasks.length;
        if(num == 0)
        {
            return;
        }
         
        //      , numb         
        for(int i=0; i num)
            {
                futureArray = new Future[num];
            }
            else
            {
                futureArray = new Future[numb];
            }
             
            //       
            ExecutorService es = Executors.newCachedThreadPool();
             
            //      ,   numb       
            for(int j=i*numb; j num)
                {
                    break;
                }
                //     ,   Future    
                futureArray[j%numb] = es.submit(tasks[j]);
            }
             
            //      result 
            if (result != null)
            {
                for (int j = 0; j < futureArray.length; j++)
                {
                    try
                    {
                        if(futureArray[j] != null)
                        {
                            Object o = futureArray[j].get();
                            result.add((T)o);
                        }
                    }
                    catch (InterruptedException e)
                    {
                        System.out.println("  Future   InterruptedException  ,  Future : " + futureArray[j].toString());
                        e.printStackTrace();
                    }
                    catch (ExecutionException e)
                    {
                        System.out.println("  Future   ExecutionException  ,  Future : " + futureArray[j].toString());
                        e.printStackTrace();
                    }
                }
            }
             
            es.shutdown();
        }
    }

==========================================================================================================================
import java.util.ArrayList;  
import java.util.List;  
import java.util.concurrent.Callable;  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
import java.util.concurrent.Future;  
  
public class Test {  
  
    public static void main(String[] args) {  
        try {  
            List list = new ArrayList<>();  
            for (int i = 0; i < 100; i++) {  
                list.add(i + ",");  
            }  
              
            System.out.println(new Test().list2Str(list, 5));  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
  
    public String list2Str(List list, final int nThreads) throws Exception {  
        if (list == null || list.isEmpty()) {  
            return null;  
        }  
          
        StringBuffer ret = new StringBuffer();  
  
        int size = list.size();  
        ExecutorService executorService = Executors.newFixedThreadPool(nThreads);  
        List> futures = new ArrayList>(nThreads);  
          
        for (int i = 0; i < nThreads; i++) {  
            final List subList = list.subList(size / nThreads * i, size / nThreads * (i + 1));  
            Callable task = new Callable() {  
                @Override  
                public String call() throws Exception {  
                    StringBuffer sb = new StringBuffer();  
                    for (String str : subList) {  
                        sb.append(str);  
                    }  
                    return sb.toString();  
                }  
            };  
            futures.add(executorService.submit(task));  
        }  
          
        for (Future future : futures) {  
            ret.append(future.get());  
        }  
        executorService.shutdown();  
          
        return ret.toString();  
    }  
}  

================================================================================================================
Callable 과 Future 의 소개
Callable 과 Future 두 가지 기능 은 자바 가 후속 버 전에 서 다 중 병합 법 에 적응 하기 위해 가입 한 것 이다. Callable 은 Runnable 과 유사 한 인터페이스 로 Callable 인 터 페 이 스 를 실현 하 는 클래스 와 Runnable 을 실현 하 는 클래스 는 모두 다른 스 레 드 에 의 해 실 행 될 수 있 는 작업 이다.
Callable 의 인터페이스 정 의 는 다음 과 같다.
public interface Callable { 

      V   call()   throws Exception; 

} 

Callable 과 Runnable 의 차 이 는 다음 과 같 습 니 다.
I    Callable 이 정의 하 는 방법 은 call 이 고 Runnable 이 정의 하 는 방법 은 run 입 니 다.
II   Callable 의 call 방법 은 반환 값 이 있 을 수 있 으 며, Runnable 의 run 방법 은 반환 값 이 있 을 수 없습니다.
III  Callable 의 call 방법 은 이상 을 던 질 수 있 으 며, Runnable 의 run 방법 은 이상 을 던 질 수 없습니다. 
미래 소개
퓨 처 는 계산 이 완 료 될 때 까지 계산 이 완료 되 었 는 지 확인 하 는 방법 을 제공 하고 계산 결 과 를 검색 하 는 비동기 계산 결 과 를 나 타 냈 다.Future 의 cancel 방법 은 작업 의 실행 을 취소 할 수 있 습 니 다. 이 매개 변 수 는 true 로 작업 의 실행 을 즉시 중단 하 는 것 을 표시 합 니 다. 매개 변 수 는 false 로 실행 중인 작업 의 실행 을 허용 합 니 다.Future 의 get 방법 은 계산 이 완료 되 기 를 기다 리 고 계산 결 과 를 가 져 옵 니 다.
import java.util.concurrent.Callable;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

/**

 * Callable   Future  

 * Callable    Runnable   ,  Callable       Runnable               。

 * Callable Runnable     :

 * (1)Callable      call(), Runnable      run().

 * (2)Callable          , Runnable          。

 * (3)call()       , run()          。

 * (4)  Callable       Future  ,

 * Future          。               ,        ,        。

 *   Future           ,        ,           。

 */

public class CallableAndFuture {

    public static class  MyCallable  implements Callable{

          private int flag = 0; 

          public MyCallable(int flag){

                  this.flag = flag;

          }

          public String call() throws Exception{

              if (this.flag == 0){  

                      return "flag = 0";

            } 

            if (this.flag == 1){   

                try {

                    while (true) {

                            System.out.println("looping.");

                            Thread.sleep(2000);

                    }

                } catch (InterruptedException e) {

                              System.out.println("Interrupted");

                }

                return "false";

            } else {   

                       throw new Exception("Bad flag value!");

            }

        }

    }

    public static void main(String[] args) {

       //   3 Callable     

        MyCallable task1 = new MyCallable(0);

        MyCallable task2 = new MyCallable(1);

        MyCallable task3 = new MyCallable(2);

        

       //            

        ExecutorService es = Executors.newFixedThreadPool(3);

        try {

           //        ,          Future  ,

            //                      Future      

            Future future1 = es.submit(task1);

           //           ,    get  ,                   

            System.out.println("task1: " + future1.get());

            

            Future future2 = es.submit(task2);

           //   5  ,        。               

            Thread.sleep(5000);

            System.out.println("task2 cancel: " + future2.cancel(true));

            

           //           ,              

            //                

            Future future3 = es.submit(task3);

            System.out.println("task3: " + future3.get());

        } catch (Exception e){

            System.out.println(e.toString());

        }

       //         

        es.shutdownNow();

    }

}

좋은 웹페이지 즐겨찾기