简单的多线程实现[Callable和Runnable]

TaskCallable.java

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.Callable;

public class TaskCallable implements Callable<TaskResult> {

    private static final Logger LOGGER = LoggerFactory.getLogger(TaskCallable.class);

    private List<String> resources;

    public TaskCallable(List<String> resources) {
        this.resources = resources;
    }

    @Override
    public TaskResult call() throws Exception {
        for (String resource : resources) {
            LOGGER.info("线程[{}]在处理数据[{}]", Thread.currentThread().getId(), resource);
            Thread.sleep(100);
            if (resource.equals("18") || resource.equals("28")) {
                throw new TaskException("处理数据[" + resource + "]时出错!");
            }
        }
        return new TaskResult(true, "线程[" + Thread.currentThread().getId() + "],处理完毕!");
    }
}

TaskRunnable.java

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.CountDownLatch;

public class TaskRunnable implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(TaskRunnable.class);

    private List<String> resources;

    private CountDownLatch latch;

    public TaskRunnable(List<String> resources, CountDownLatch latch) {
        this.resources = resources;
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            for (String resource : resources) {
                LOGGER.info("线程[{}]在处理数据[{}]", Thread.currentThread().getId(), resource);
                Thread.sleep(100);
                if (resource.equals("19") || resource.equals("29")) {
                    throw new TaskException("处理数据[" + resource + "]时出错!");
                }
            }
        } catch (TaskException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            latch.countDown();
        }
    }
}

TaskResult.java

public class TaskResult {
    public TaskResult(boolean success) {
        this(success, null, null);
    }

    public TaskResult(boolean success, String msg) {
        this(success, msg, null);
    }

    public TaskResult(boolean success, String msg, Object data) {
        this.success = success;
        this.msg = msg;
        this.data = data;
    }

    private boolean success;
    private String msg;
    private Object data;

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

TaskException.java

public class TaskException extends Exception {

    public TaskException(String message) {
        super(message);
    }

    public TaskException(String message, Throwable cause) {
        super(message, cause);
    }
}

TaskTest.java

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.*;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;

public class TaskTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(TaskTest.class);
    private static final ListeningExecutorService les = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(3));

    @Test
    public void doRunTest() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 42; i++) {
            list.add(String.valueOf(i));
        }
        List<List<String>> partition = Lists.partition(list, 5);
        final CountDownLatch latch = new CountDownLatch(partition.size());

        for (List<String> part : partition) {
            //Runnable实现
            //les.execute(new TaskRunnable(part, latch));
            //Callable实现
            process(part, latch);
        }
        try {
            LOGGER.info("等待子线程执行完毕……");
            latch.await();
            LOGGER.info("子线程执行完毕……");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        les.shutdown();
    }

    private void process(List<String> executeList, final CountDownLatch latch) {
        ListenableFuture<TaskResult> taskResultListenableFuture = les.submit(new TaskCallable(executeList));
        Futures.addCallback(taskResultListenableFuture, new FutureCallback<TaskResult>() {
            @Override
            public void onSuccess(TaskResult taskResult) {
                if (taskResult.isSuccess()) {
                    LOGGER.info(taskResult.getMsg());
                }
                latch.countDown();
            }

            @Override
            public void onFailure(Throwable throwable) {
                LOGGER.error(throwable.getMessage());
                latch.countDown();
            }
        });
    }
}

猜你喜欢

转载自blog.csdn.net/cx118118/article/details/80484014