java中JUC多线程的方式有哪些

这篇文章将为大家详细讲解有关java中JUC多线程的方式有哪些,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Author:MuJiuTian
 * @Description:
 * @Date: Created in 下午2:42 2019/7/29
 */
public class Test1 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //testThreadPool();
        testThreadPool();
    }

    public static void testThreadPool(){
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        List<Future<List<Integer>>> list= new ArrayList<>();
        for (int i = 0;i<10; i++){
            Future<List<Integer>> future = executorService.submit(new MyCallable());
            list.add(future);
        }

        list.forEach(n -> {
            try {
                System.out.println(n.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });

    }

    public static void testMyCallable() throws ExecutionException, InterruptedException {
        FutureTask futureTask = new FutureTask<>(new MyCallable());
        new Thread(futureTask).start();
        List<Integer> list = (List<Integer>) futureTask.get();
        list.forEach(n -> System.out.println(n));
    }

    public static void testMyRunnable(){
        new Thread(new MyRunnable()).start();
    }

    public static void testMythread(){
        new MyThread().start();
    }

}

//多线程第一种方式:继承Thread类
class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("输出mythread");
    }
}

//多线程第二种方式:java单继承,继承了其他类,只能实现根类Runnable
class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("输出没有runnable");
    }
}

//多线程第三种方式:Callable接口
class MyCallable implements Callable<List<Integer>>{
    @Override
    public List<Integer> call() throws Exception {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i<10; i++){
            list.add(i);
        }
        return list;
    }
}

2、多线程并发

线程的常用方法介绍

JAVA多线程之间实现同步+多线程并发同步解决方案

Synchronized、ReentrantLock(可重入锁)、ReentrantReadWriteLock(读写锁)

CyclicBarrier、Semaphore、concurrentHashMap和BlockingQueue。

关于“java中JUC多线程的方式有哪些”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。