欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java多线程与线程池

程序员文章站 2022-07-03 19:32:17
说明:本文主要是线程的四种启动方法,第四种是线程池,如若想查找线程池相关资料,可以忽略前面三种。方法一:继承extends类,没有返回结果public class ThreadTestOne { public static void main(String args[]){ System.out.println("main...........start"); Thread01 thread01 = new Thread01(); thre...

说明:本文主要是线程的四种启动方法,第四种是线程池,如若想查找线程池相关资料,可以忽略前面三种。

区别:方法一二不能得到返回值,方法三四可以获取返回值,方法一二三都不能控制资源,方法四可以控制资源且性能稳定。

方法一:继承extends类,没有返回结果

public class ThreadTestOne {

    public static void main(String args[]){
        System.out.println("main...........start");
        Thread01 thread01 = new Thread01();
        thread01.run();
        System.out.println("main...........end");
    }

    public static class Thread01 extends Thread{
        public void run(){
            System.out.println("当前线程名称..........."+ Thread.currentThread().getId());
            int i = 10/2;
            System.out.println("当前线程运行结果..........."+i);
        }
    }
}

方法二:实现Runnable接口,没有返回结果

public class ThreadTestTwo {

    public static void main(String args[]){
        System.out.println("main..........start");
        Runable01 runable01 = new Runable01();
        runable01.run();
        System.out.println("main..........end");
    }

    public static class Runable01 implements Runnable{
        @Override
        public void run() {
            System.out.println("当前线程名称..........." + Thread.currentThread().getId());
            int i = 10/2;
            System.out.println("当前线程运行结果..........." + i);
        }
    }

}

方法三:实现Callable接口,有返回结果

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadTestThr {

    public static void main(String args[]) throws ExecutionException, InterruptedException {
        System.out.println("main...........start");

        FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable01());
        new Thread(futureTask).start();
        Integer i = futureTask.get();

        System.out.println("main...........end   "+ i);
    }

    public static class Callable01 implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            System.out.println("当前线程名称..........." + Thread.currentThread().getId());
            int i = 10/2;
            System.out.println("当前线程运行结果..........." + i);
            return i;
        }
    }

}

方法四:使用线程池,该方法中存在着多种方式

方式A://能获取到上一步的结果 //这里可以处理上面方法完成返回的结果 //不能返回结果

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 李庆伟
 * @date 2020/12/30 15:12
 */
public class ThreadFour {
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String args[]) throws ExecutionException, InterruptedException {
        System.out.println("main...........start");

        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(()->{
            System.out.println("当前线程名称..........." + Thread.currentThread().getId());
            int i = 10/5;
            //int i = 10/0;
            System.out.println("当前线程运行结果..........." + i);
            return i;
        },executor).whenComplete((res,exception)->{
            //能获取到上一步的结果
            //这里可以处理上面方法完成返回的结果
            //不能返回结果
            System.out.println("完成异步任务......res为" + res + ", 异常是 "+ exception);
        });
        Integer i = future.get();//得到的是原来的结果
        System.out.println("main...........end......" + i);
    }
}

方式B://能获取到上一步的结果 //这里可以处理上面方法完成返回的结果 //返回结果

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 李庆伟
 * @date 2020/12/30 15:12
 */
public class ThreadFive {
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String args[]) throws ExecutionException, InterruptedException {
        System.out.println("main...........start");

        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(()->{
            System.out.println("当前线程名称..........." + Thread.currentThread().getId());
            int i = 10/10;
            //int i = 10/0;
            System.out.println("当前线程运行结果..........." + i);
            return i;
        },executor).handle((res,exception)->{
            //能获取到上一步的结果
            //这里可以处理上面方法完成返回的结果
            //有返回结果
            System.out.println("完成异步任务......res为" + res + ", 异常是 "+ exception);
            if(res == 1){
                return 10;
            } else {
                return res;
            }
        });
        Integer i = future.get();//得到的是处理后的结果
        System.out.println("main...........end......" + i);
    }
}

方式C://不能获取到上一步的结果

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 李庆伟
 * @date 2020/12/30 15:12
 */
public class ThreadSix {
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String args[]) {
        System.out.println("main...........start");
        CompletableFuture<Void> future = CompletableFuture.supplyAsync(()->{
            System.out.println("当前线程名称..........." + Thread.currentThread().getId());
            int i = 10/4;
            System.out.println("当前线程运行结果..........." + i);
            return i;
        },executor).thenRunAsync(()->{
            //不能获取到上一步的结果
            System.out.println("完成异步任务......");
        },executor);
        System.out.println("main...........end......");
    }
}

方式D://能获取到上一步的结果//没有返回值

 

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 李庆伟
 * @date 2020/12/30 15:12
 */
public class ThreadSeven {
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String args[]) {
        System.out.println("main...........start");
        CompletableFuture<Void> future = CompletableFuture.supplyAsync(()->{
            System.out.println("当前线程名称..........." + Thread.currentThread().getId());
            int i = 10/3;
            System.out.println("当前线程运行结果..........." + i);
            return i;
        },executor).thenAcceptAsync((res)->{
            //能获取到上一步的结果//没有返回值
            System.out.println("完成异步任务......" + res);
        },executor);
        System.out.println("main...........end......");
    }

}

方式E://能获取到上一步的结果//有返回值

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 李庆伟
 * @date 2020/12/30 15:12
 */
public class ThreadEight {
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String args[]) throws ExecutionException, InterruptedException {
        System.out.println("main...........start");
        CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
            System.out.println("当前线程名称..........." + Thread.currentThread().getId());
            int i = 10/3;
            System.out.println("当前线程运行结果..........." + i);
            return i+"";
        },executor).thenApplyAsync((res)->{
            //能获取到上一步的结果//有返回值
            System.out.println("完成异步任务......" + res);
            return res + " hello";
        },executor);
        String str = future.get();
        System.out.println("main...........end......" + str);
    }

}

方式F://综合Demo

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 李庆伟
 * @date 2020/12/30 15:12
 */
public class ThreadDemo {
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String args[]) throws ExecutionException, InterruptedException {

        String str = "hello";

        //异步1,  2和3需要依赖1  4独立
        CompletableFuture<String> futureOne = CompletableFuture.supplyAsync(()->{
            String one = str + " world + futureOne";
            return one;
        },executor);

        CompletableFuture<String> futureTwo = futureOne.thenApplyAsync((res)->{
            String two = res + " + futureTwo";
            return two;
        },executor);

        CompletableFuture<String> futureThr = futureOne.thenApplyAsync((res)->{
            String thr = res + " + futureThr";
            return thr;
        },executor);

        CompletableFuture<String> futureFou = CompletableFuture.supplyAsync(()->{
            String fou = str + " + futureFou";
            return fou;
        },executor);


        // 等到所有任务都完成
        CompletableFuture.allOf(futureOne, futureTwo, futureThr, futureFou).get();

        System.out.println(futureOne.get());
        System.out.println(futureTwo.get());
        System.out.println(futureThr.get());
        System.out.println(futureFou.get());
    }

}

记录一点。。。。。。。。。。

 

 

 

 

本文地址:https://blog.csdn.net/liqingwei168/article/details/111981159