实现多线程有以下四种方式

实现多线程有以下四种方式:
1. 继承Thread类

2.实现Runnable接口

3.实现Callable接口

4.线程池:提供了一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁额外开销,提高了响应的速度。

体系结构:

java.util.concurrent.Executor : 负责线程的使用与调度的根接口
  |–ExecutorService 子接口: 线程池的主要接口
    |–ThreadPoolExecutor 线程池的实现类
    |–ScheduledExecutorService 子接口:负责线程的调度
      |–ScheduledThreadPoolExecutor :继承 ThreadPoolExecutor, 实现 ScheduledExecutorService *

工具类 : Executors
ExecutorService newFixedThreadPool() : 创建固定大小的线程池
ExecutorService newCachedThreadPool() : 缓存线程池,线程池的数量不固定,可以根据需求自动的更改数量。
ExecutorService newSingleThreadExecutor() : 创建单个线程池。线程池中只有一个线程
ScheduledExecutorService newScheduledThreadPool() : 创建固定大小的线程,可以延迟或定时的执行任务。

1) 继承Thread类

package com.lxj.juc;
 
public class TestThread {
     public static void main(String[] args) {
         ThreadDemo threadDemo = new ThreadDemo();
         threadDemo.start();
     }
}
 
 
class  ThreadDemo extends Thread{
 
    @Override
    public void run() {
        boolean flag = false;
        for(int i  = 3 ; i < 100 ; i ++) {
            flag = false;
            for(int j = 2; j <= Math.sqrt(i) ; j++) {
                if(i % j == 0) {
                    flag = true;
                    break;
                }
            }
            if(flag == false) {
                System.out.print(i+"  ");
            }
        }
    }
  
     
}

运行结果:
3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

2)实现Runnable接口

package com.lxj.juc;
 
public class TestRunnable {
    public static void main(String[] args) {
        RunnableDemo runnableDemo = new RunnableDemo();
        new Thread(runnableDemo).start();
    }
}
 
class RunnableDemo implements Runnable{
 
    @Override
    public void run() {
        boolean flag = false;
        for(int i  = 3 ; i < 100 ; i ++) {
            flag = false;
            for(int j = 2; j <= Math.sqrt(i) ; j++) {
                if(i % j == 0) {
                    flag = true;
                    break;
                }
            }
            if(flag == false) {
                System.out.print(i+"  ");
            }
        }
    }
    
}

运行结果:
3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

3)实现Callable接口

package com.lxj.juc;
 
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
 
public class TestCallable1 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        CallableDemo callableDemo = new CallableDemo();
        FutureTask futureTask = new FutureTask<>(callableDemo); 
        new Thread(futureTask).start();
        List<Integer> lists = (List<Integer>)futureTask.get(); //获取返回值
        for (Integer integer : lists) {
            System.out.print(integer + "  ");
        }
    }
}
 
class CallableDemo implements Callable<List<Integer>>{
 
    @Override
    public List<Integer> call() throws Exception {
        boolean flag = false;
        List<Integer> lists = new ArrayList<>();
        for(int i  = 3 ; i < 100 ; i ++) {
            flag = false;
            for(int j = 2; j <= Math.sqrt(i) ; j++) {
                if(i % j == 0) {
                    flag = true;
                    break;
                }
            }
            if(flag == false) {
                lists.add(i);
            }
        }
        return lists;
    }
    
}

运行结果:
3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

4) 线程池

package com.lxj.juc;
 
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
 
public class TestThreadPool {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        List<Future<List<Integer>>> ints = new ArrayList<>();
        for(int i = 0 ; i < 5; i ++) {
            Future<List<Integer>> future = executorService.submit(new Callable<List<Integer>>() {
                @Override
                public List<Integer> call() throws Exception {
                    boolean flag = false;
                    System.out.println(Thread.currentThread().getName()+"  ");
                    List<Integer> lists = new ArrayList<>();
                    for(int i  = 3 ; i < 100 ; i ++) {
                        flag = false;
                        for(int j = 2; j <= Math.sqrt(i) ; j++) {
                            if(i % j == 0) {
                                flag = true;
                                break;
                            }
                        }
                        if(flag == false) {
                            lists.add(i);
                        }
                    }
                    return lists;
                }
            });
            ints.add(future);
        }
        
        for (Future<List<Integer>> future : ints) {
            System.out.println(future.get());
        }
    }
}
 
class ThreadPoolDemo {
 
}

运行结果:
pool-1-thread-2
pool-1-thread-5
pool-1-thread-3
pool-1-thread-1
pool-1-thread-4
[3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
[3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
[3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
[3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
[3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

以上即为创建多线程的4种方式。

 

 

————————————————
版权声明:本文为CSDN博主「刘信坚的博客」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38974634/article/details/81315900

原文地址:http://www.cnblogs.com/big-keyboard/p/16813151.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性