zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【Java】+多线程

2023-09-11 14:16:50 时间

Java创建多线程的8种方式:https://blog.csdn.net/itcats_cn/article/details/81149232

 

一、多个带返回值的线程

import java.util.concurrent.*;

/**
 * @Author : 
 * @Date : 
 * @Description :
 *
 * <p>
 * step1 创建一个类 这个类中的call为需要让线程做的事
 * step2 线程调用时 直接new一个step1中的对象即可(new之后 自动执行对象中的call方法)
 * 备注:若做的事需要参数化传递 则以类属性的方式传给call
 * shutdown方法: 这个方法,只能立刻interrupt那些目前没有任务,处于等待状态从blockingQueue获取任务的异常。而不能interrupt那些在任务执行过程中的thread,或者是任务执行过程中挂起的thread。
 * shutdownNow方法: 不管任务是否在执行中,一律interrupt,不去判断什么锁不锁。
 *
 * @Version :
 */
class Task implements Callable<Integer> {
    private Integer taskID = 1;

    public Task(Integer taskID) {
        this.taskID = taskID;
    }

    /**
     * 需要线程做的事
     *
     * @return
     * @throws Exception
     */
    public Integer call() throws Exception {
        if (taskID.equals(3) || taskID.equals(5) || taskID.equals(6)) Thread.sleep(5000);
        System.out.println("任务[" + taskID + "]开始执行");
        return taskID;
    }


    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Integer poolCount = 10; // 线程数
        Integer taskCount = 7; // 任务数
        // 1 创建一个线程池
        ExecutorService pools = Executors.newFixedThreadPool(poolCount);
        CompletionService<Integer> s = new ExecutorCompletionService<Integer>(pools);
        // 2 创建多个有返回值的任务
        for (int i = 0; i <= taskCount; i++) {
            s.submit(new Task(i));
        }
        // 3 打印每个任务的返回值
        for (int i = 0; i <= taskCount; i++) {
            try {
                Future<Integer> f = s.take();
                Integer integer = f.get();
                // 可以在这里判断一下线程的执行结果 若是想要的结果 并且不想让后面的未执行或正在执行的线程运行了 则可以使用shutdownNow直接结束
                System.out.println(integer);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        // 4 关闭线程池
        pools.shutdown();
    }
}

 

二、线程状态

参考

NEW(新建状态)
RUNNABLE(可运行/就绪状态)
BLOCKED(阻塞状态)
WAITING(等待状态)
TIMED_WAITING(定时等待)
TERMINATED(终止状态)