当前位置:   article > 正文

Java获取多线程的4种方式_java 获取电脑被使用的线程数

java 获取电脑被使用的线程数

1、实现Runnable接口

  1. package com.atguigu.thread;
  2. /**
  3. * @author bjk
  4. * @date 2021/09/02 18:05
  5. *
  6. * 一个类实现Runnable接口
  7. */
  8. class Mythread implements Runnable{
  9. @Override
  10. public void run() {
  11. System.out.println("hello");
  12. }
  13. }
  14. public class ThreadDemo1 {
  15. public static void main(String[] args) {
  16. Mythread mythread = new Mythread();
  17. Thread thread = new Thread(mythread);
  18. thread.start();
  19. }
  20. }

2、继承Thread

  1. package com.atguigu.thread;
  2. import java.util.concurrent.Callable;
  3. /**
  4. * @author bjk
  5. * @date 2021/09/02 18:07
  6. * 继承Thread创建线程
  7. */
  8. class Mythread2 extends Thread {
  9. @Override
  10. public void run() {
  11. System.out.println("hello");
  12. }
  13. }
  14. public class ThreadDemo2 {
  15. public static void main(String[] args) {
  16. Mythread2 mythread2 = new Mythread2();
  17. mythread2.start();
  18. }
  19. }

3、实现Callable接口

这个方法可以有返回值的,比Runnable功能强大

  1. package com.atguigu;
  2. import java.util.concurrent.Callable;
  3. import java.util.concurrent.ExecutionException;
  4. import java.util.concurrent.FutureTask;
  5. /**
  6. * @author bjk
  7. * @date 2021/09/02 18:19
  8. */
  9. //多接口实现
  10. class Mythread1 implements Callable<String>, Runnable {
  11. @Override
  12. public String call() throws Exception {
  13. System.out.println("call");
  14. return "call";
  15. }
  16. @Override
  17. public void run() {
  18. }
  19. }
  20. //构造注入
  21. class Mythread implements Callable<Integer>{
  22. @Override
  23. public Integer call() throws Exception {
  24. System.out.println("come-------call");
  25. return 2222;
  26. }
  27. }
  28. public class CallableDemo {
  29. public static void main(String[] args) throws Exception {
  30. FutureTask futureTask =new FutureTask(new Mythread());
  31. new Thread(futureTask,"A").start();
  32. System.out.println(futureTask.get());
  33. }
  34. }

 4、通过线程池获取线程

        

  1. public ThreadPoolExecutor threadPoolExecutor (){
  2. // 看cpu 密集型 n+1,还是io 密集型:2*n 核心线程数
  3. //7个参数 [初始化线程数 ,最大线程数 ,最大等待时长(回收最大线程数的参数)
  4. //, 时间单位 , 阻塞队列 , 线程工厂(可省略) , 拒绝策略(可省略,默认抛异常 ) ]
  5. ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(8, 20, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000));
  6. return poolExecutor;
  7. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/58821
推荐阅读
相关标签
  

闽ICP备14008679号