JAVA 线程实现/创建方式

2020-04-25  本文已影响0人  奶盐味小圆饼

1. 继承 Thread 类

Thread 类本质上是实现了 Runnable 接口的一个实例,代表一个线程的实例。启动线程的唯一方法就是通过 Thread 类的 start()实例方法。start()方法是一个 native 方法,它将启动一个新线程,并执行 run()方法.

public class ThreadTest{

    /**
     * java里面static一般用来修饰成员变量或函数。
     * 但有一种特殊用法是用static修饰内部类,
     * 普通类是不允许声明为静态的,只有内部类才可以。
     */
    private static class MyThread extends Thread {
        
        public void run() {
            System.out.println("MyThread.run()");
        }
    }

    public static void main(String[] args) {
        MyThread myThread1 = new MyThread();
        myThread1.start();

        /**
         * 直接通过ThreadTest类名访问静态内部类MyThread
         */
        MyThread my = new ThreadTest.MyThread();
        my.run();
    }
}

2. 实现 Runnable 接口

如果自己的类已经 extends 另一个类,就无法直接 extends Thread,此时,可以实现一个Runnable 接口.

public class RunnableTest {

    public static class MyThread1 implements Runnable {
        public void run() {
            System.out.println("MyThread.run()");
        }
    }

    public static void main(String[] args) {
        /**
         * 启动 MyThread,需要首先实例化一个 Thread,并传入自己的 MyThread 实例:
         */
        MyThread1 myThread = new MyThread1();
        Thread thread = new Thread(myThread);
        thread.start();

        /**
         * 事实上,当传入一个 Runnable target 参数给 Thread 后,Thread 的 run()方法就会调用target.run()
         * public void run() {
         *  if (target != null) {
         *  target.run();
         *  }
         * }
         */
        thread.run();
    }
}

3. ExecutorService、Callable<Class>、Future 有返回值线程

有返回值的任务必须实现 Callable 接口,类似的,无返回值的任务必须 Runnable 接口。执行Callable 任务后,可以获取一个 Future 的对象,在该对象上调用 get 就可以获取到 Callable 任务返回的 Object 了,再结合线程池接口 ExecutorService 就可以实现传说中有返回结果的多线程了。

public class MyCallable implements Callable<String> {
    private String s;
    public MyCallable(String s) {

        this.s = s;
    }

    @Override
    public String call() throws Exception {
        return s;
    }
}
public class CallRunnableTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建一个线程池
        ExecutorService pool = Executors.newFixedThreadPool(10);
        // 创建多个有返回值的任务
        List<Future<String>> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Callable<String> c = new MyCallable(i + " ");
        // 执行任务并获取 Future 对象
            Future<String> f = pool.submit(c);
            list.add(f);
        }
        // 关闭线程池
        pool.shutdown();
        // 获取所有并发任务的运行结果
        for (Future<String> f : list) {
        // 从 Future 对象上获取任务的返回值,并输出到控制台
            System.out.println("res:" + f.get());
        }
    }
}

start 与 run 区别

  1. start()方法来启动线程,真正实现了多线程运行。这时无需等待 run 方法体代码执行完毕,可以直接继续执行下面的代码。

  2. 通过调用 Thread 类的 start()方法来启动一个线程, 这时此线程是处于就绪状态, 并没有运行。

  3. 方法 run()称为线程体,它包含了要执行的这个线程的内容,线程就进入了运行状态,开始运行 run 函数当中的代码。 Run 方法运行结束, 此线程终止。然后 CPU 再调度其它线程。

sleep 与 wait 区别

  1. 对于 sleep()方法,我们首先要知道该方法是属于 Thread 类中的。而 wait()方法,则是属于Object 类中的。

  2. sleep()方法导致了程序暂停执行指定的时间,让出 cpu 该其他线程,但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。

  3. 在调用 sleep()方法的过程中,线程不会释放对象锁。

  4. 而当调用 wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用 notify()方法后本线程才进入对象锁定池准备获取对象锁进入运行状态。

上一篇下一篇

猜你喜欢

热点阅读