2018-12-02  本文已影响6人  panzhangbao
  1. 什么是线程?

线程是 CPU 的基本单位。
一个进程中有多个线程,多个线程共享进程的堆和方法区资源,但是每个线程都有自己的程序计数器和栈区域。

  1. 线程的创建方式(三种)

调用 start() 方法后并没有马上执行,而是处于就绪状态(该线程已经获取了除 CPU 资源外的其他资源,等待获取 CPU 资源后才会真正处于运行状态)。

一旦 run() 方法执行完毕后,该线程就处于终止状态。

优点:在 run() 方法内获取当前线程直接使用this即可。
缺点: Java 不支持多继承;任务与代码没有分离,当多个线程执行一样的任务时,需要多份任务代码。

    /**
     * 1. 继承 Thread 类并重写 run 方法
     */
    public static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("I'm a child thread, and extends Thread class, the method is run()");
        }
    }
    
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
    }
  1. 实现 Runnable 接口的 run 方法

优点:多个线程可以共用一个task代码逻辑,如果需要,可以给MyRunnable添加参数进行区分;
MyRunnable可以继承其他类。
缺点:任务没有返回值

    /**
     * 2. 实现 Runnable 接口的 run 方法
     */
    public static class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("I'm a child thread, and implement Runnable's run() method");
        }
    }

    public static void main(String[] args) {       
        MyRunnable myRunnable = new MyRunnable();
        new Thread(myRunnable).start();
        new Thread(myRunnable).start();
    }
  1. 使用 FutureTask 的方式,实现 Callablecall() 方法
    /**
     * 3. 使用 FutureTask 的方式
     */
    public static class CallerTask implements Callable<String> {

        @Override
        public String call(){
            return "Hello";
        }
    }

    public static void main(String[] args) {
        // 创建异步任务
        FutureTask<String> stringFutureTask = new FutureTask<>(new CallerTask());
        new Thread(stringFutureTask).start();
        try {
            // 等待任务执行完毕,并返回结果
            String result = stringFutureTask.get();
            System.out.println(result);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读