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

我们拥有十多年网页设计和网站建设经验,从网站策划到网站制作,我们的网页设计师为您提供的解决方案。为企业提供成都网站设计、成都做网站、外贸网站建设、微信开发、微信小程序开发、手机网站制作、H5开发、等业务。无论您有什么样的网站设计或者设计方案要求,我们都将富于创造性的提供专业设计服务并满足您的需求。
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>> list= new ArrayList<>();
for (int i = 0;i<10; i++){
Future> 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 list = (List) 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>{
@Override
public List call() throws Exception {
List 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多线程的方式有哪些”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。