赞
踩
- package com.atguigu.thread;
-
- /**
- * @author bjk
- * @date 2021/09/02 18:05
- *
- * 一个类实现Runnable接口
- */
-
- class Mythread implements Runnable{
-
- @Override
- public void run() {
- System.out.println("hello");
- }
- }
- public class ThreadDemo1 {
- public static void main(String[] args) {
- Mythread mythread = new Mythread();
- Thread thread = new Thread(mythread);
- thread.start();
- }
-
- }


- package com.atguigu.thread;
-
- import java.util.concurrent.Callable;
-
- /**
- * @author bjk
- * @date 2021/09/02 18:07
- * 继承Thread创建线程
- */
- class Mythread2 extends Thread {
- @Override
- public void run() {
- System.out.println("hello");
- }
- }
- public class ThreadDemo2 {
- public static void main(String[] args) {
- Mythread2 mythread2 = new Mythread2();
- mythread2.start();
- }
- }


这个方法可以有返回值的,比Runnable功能强大
- package com.atguigu;
-
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.FutureTask;
-
- /**
- * @author bjk
- * @date 2021/09/02 18:19
- */
- //多接口实现
- class Mythread1 implements Callable<String>, Runnable {
- @Override
- public String call() throws Exception {
- System.out.println("call");
- return "call";
- }
-
- @Override
- public void run() {
-
- }
- }
- //构造注入
- class Mythread implements Callable<Integer>{
-
- @Override
- public Integer call() throws Exception {
- System.out.println("come-------call");
- return 2222;
- }
- }
-
-
- public class CallableDemo {
- public static void main(String[] args) throws Exception {
- FutureTask futureTask =new FutureTask(new Mythread());
- new Thread(futureTask,"A").start();
- System.out.println(futureTask.get());
- }
-
- }


- public ThreadPoolExecutor threadPoolExecutor (){
- // 看cpu 密集型 n+1,还是io 密集型:2*n 核心线程数
- //7个参数 [初始化线程数 ,最大线程数 ,最大等待时长(回收最大线程数的参数)
- //, 时间单位 , 阻塞队列 , 线程工厂(可省略) , 拒绝策略(可省略,默认抛异常 ) ]
- ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(8, 20, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000));
- return poolExecutor;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。