温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-11-17 09:30:19 来源:亿速云 阅读:130 作者:小新 栏目:大数据

这篇文章将为大家详细讲解有关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多线程的方式有哪些”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI