スレッド実装CallableインタフェースとRunnableインタフェースの比較


1.スレッドタスクはRunnableインタフェースを継承する方法
package com.thread;

/**
 * @author liuchj
 * @version 1.0
 * @className MyThreadTest
 * @description //TODO
 * @date 2019/5/29
 **/

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolTask {

    /**
     *        
     */
    static Queue queue = new ConcurrentLinkedQueue();

    static {
        //   
        for (int i = 0; i < 9; i++) {
            queue.add("task-" + i);
        }
    }

    public static void main(String[] args) {
        MyThreadFactory threadFactory = new MyThreadFactory();
        //     
        ExecutorService executor = new ThreadPoolExecutor(5, 5,
                10L, TimeUnit.SECONDS,
                new LinkedBlockingQueue(), threadFactory);

        List futureRunnable = new ArrayList<>(10);
        for (int i = 0; i < queue.size(); i++) {
            Future> future = executor.submit(new InnerThreadRunnable());
            futureRunnable.add(future);
        }

        for (Object future : futureRunnable) {
            System.out.println("result = " + future);
        }
        //          
        executor.shutdown();

    }
}



/**
 *   :          
 */
class InnerThreadRunnable implements Runnable {

    @Override
    public void run() {

        //   
        while (ThreadPoolTask.queue.size() > 0) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String value = ThreadPoolTask.queue.poll();
            if (value != "" && null != value) {
                System.out.println("  " + Thread.currentThread().getName() + "    task: " + value);
            }
        }
    }
}


class MyThreadFactory implements ThreadFactory {
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    public MyThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();

        namePrefix = "Thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        return t;
    }
}


実行結果:
  Thread-5    task: task-0
  Thread-1    task: task-3
  Thread-2    task: task-4
  Thread-3    task: task-2
result = java.util.concurrent.FutureTask@14899482
  Thread-4    task: task-1
  Thread-5    task: task-6
  Thread-3    task: task-5
  Thread-4    task: task-8
  Thread-1    task: task-7
result = java.util.concurrent.FutureTask@21588809
result = java.util.concurrent.FutureTask@2aae9190
result = java.util.concurrent.FutureTask@2f333739
result = java.util.concurrent.FutureTask@77468bd9
result = java.util.concurrent.FutureTask@12bb4df8
result = java.util.concurrent.FutureTask@4cc77c2e
result = java.util.concurrent.FutureTask@7a7b0070
result = java.util.concurrent.FutureTask@39a054a5

2.スレッドタスクはCallableインタフェースを継承する方法
package com.thread;

/**
 * @author liuchj
 * @version 1.0
 * @className MyThreadTest
 * @description //TODO
 * @date 2019/5/29
 **/

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolTask {

    /**
     *        
     */
    static Queue queue = new ConcurrentLinkedQueue();

    static {
        //   
        for (int i = 0; i < 9; i++) {
            queue.add("task-" + i);
        }
    }


    public static void main(String[] args) {
        MyThreadFactory threadFactory = new MyThreadFactory();
        //     
        ExecutorService executor = new ThreadPoolExecutor(5, 5,
                10L, TimeUnit.SECONDS,
                new LinkedBlockingQueue(), threadFactory);

        List> futures = new ArrayList>(10);

        for (int i = 0; i < queue.size(); i++) {
            Future future = executor.submit(new InnerThreadCallable());
            futures.add(future);
        }

        for (Future future : futures) {
            try {
                String result = future.get();
                System.out.println("result = " + result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        //          
        executor.shutdown();

    }
}


/**
 *   :          
 */
class InnerThreadCallable implements Callable {

    @Override
    public String call() throws Exception {
        //   
        while (ThreadPoolTask.queue.size() > 0) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String value = ThreadPoolTask.queue.poll();
            if (value != "" && null != value) {
                System.out.println("  " + Thread.currentThread().getName() + "    task: " + value);
            }
        }
        return "run";
    }
}

class MyThreadFactory implements ThreadFactory {
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    public MyThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();

        namePrefix = "Thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        return t;
    }
}


実行結果:
  Thread-4    task: task-0
  Thread-3    task: task-1
  Thread-2    task: task-2
  Thread-1    task: task-3
  Thread-5    task: task-4
  Thread-4    task: task-5
  Thread-3    task: task-6
  Thread-1    task: task-7
  Thread-5    task: task-8
result = run
result = run
result = run
result = run
result = run
result = run
result = run
result = run
result = run