线程实现Callable接口和Runnable接口的对比

博客介绍了线程任务的两种实现方式,分别是继承Runnable接口和继承Callable接口,并提及了相应的运行和执行结果。

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<String> queue = new ConcurrentLinkedQueue<String>();

    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<Runnable>(), 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<String> queue = new ConcurrentLinkedQueue<String>();

    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<Runnable>(), threadFactory);

        List<Future<String>> futures = new ArrayList<Future<String>>(10);

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

        for (Future<String> 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<String> {

    @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

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蹉跎之人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值