• Java 创建线程的三种方式


    Java 创建线程的多种方式

    1. 继承 Thread 类(不推荐)

    继承 Thread 类的方法:

    public class Type1 {
        public static void main(String[] args) throws InterruptedException {
            MyThread thread = new MyThread();
            MyThread thread2 = new MyThread();
            
            thread.start();
            thread2.start();
            
            System.out.println(thread);
            System.out.println(thread2);
        }
    }
    
    
    /**
     * 1. 继承 Thread 类
     */
    class MyThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                System.out.print(i + " ");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    这种方法有个缺点,因为 Java 只能单继承,所以如果如果只要继承了 Thread 类,就不能再继承其他类了,失去了可扩展性。

    Java 可以实现继承和实现,若继承了 Thread 就无法继承其他类了:

    class Test extends Object implements TestIn {}
    
    • 1

    2. 实现 Runnable 接口

    实现 Runnable 接口方法:

    public class Type2 {
    
        public static void main(String[] args) {
            Thread thread = new Thread(new MyThread(), "task1");
            Thread thread2 = new Thread(new MyThread(), "task2");
    
            thread.start();
            thread2.start();
    
            System.out.println(thread);
            System.out.println(thread2);
        }
    
    }
    
    /**
     * 2. 实现 Runnable 接口
     */
    class MyThread implements Runnable {
    
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                System.out.print(i + " ");
            }
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    实现 Runnable 接口,这样解决了继承 Thread 所带来的缺点。用实现 Runnable 的类去初始化 Thread 即可。

    3. 实现 Callable 接口

    Runnable 接口无法实现的功能:当线程终止时(即 run() 完成时),我们无法使线程反回结果。为了支持此功能,Java 中提供了 Callable 接口。

    • 实现 Callable 接口的 call() 方法,可以抛出异常,并且具有返回值。

    Runnable 接口有个实现类 FutureTaskFutureTask 构造可以传递实现 Callable 接口的对象。

    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.FutureTask;
    
    public class Type3 {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            FutureTask<Integer> task1 = new FutureTask<>(new MyThread());
            FutureTask<Integer> task2 = new FutureTask<>(()->{
                int s = 0;
                for (int i = 1; i <= 100; i++) {
                    s += i;
                }
                System.out.println(Thread.currentThread().getName() + " completed!");
                Thread.sleep(1000);
                return s;
            });
    
            Thread thread = new Thread(task1, "t1");
            Thread thread2 = new Thread(task2, "t2");
    
            thread.start();
            thread2.start();
    
            while (!task1.isDone()) {
                System.out.println("task1 waiting....");
            }
    
    
            System.out.println(task1.get());
            System.out.println(task2.get());
            System.out.println(Thread.currentThread().getName() + " completed!");
        }
    }
    
    
    class MyThread implements Callable<Integer> {
    
        @Override
        public Integer call() throws Exception {
            int s = 0;
            for (int i = 1; i < 200; i++) {
                s += i;
            }
            System.out.println(Thread.currentThread().getName() + " completed!");
            return s;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    在这里插入图片描述

    附录

    可以设置优先级 [1-10],默认为 5,10 优先级最高。

    计算代码运行时间:

    long start = System.currentTimeMillis();
    long end = System.currentTimeMillis();
    System.out.println("共耗时"+ (end - start) +"毫秒");
    
    • 1
    • 2
    • 3
  • 相关阅读:
    技巧分享:wps文件怎么转换成word格式?
    6277: 【区赛】【鄞州2022】最小差值
    虚幻引擎4利用粒子系统实现物体轨迹描绘2- 消除轨迹
    UNION、UNION ALL的使用练习题 【牛客-SQL必知必会】13 组合查询
    面试题:在大型分布式系统中,给你一条 SQL,让你优化,你会怎么做?
    递归神经网络 (RNN)
    你知道有哪些类型的接口吗?
    思维分析逻辑 1 DAY
    MySQL 主从复制与读写分离
    JS的继承
  • 原文地址:https://blog.csdn.net/qq_39906884/article/details/126800381