Java创建多线程的4种方式 与 线程状态

线程的状态

在进行多线程编程之前,要先知道线程都有哪几种状态。

线程的状态在 java.lang.Thread.State 有定义:

/**

    * A thread state.  A thread can be in one of the following states:

    *

        *

  • {@link #NEW}

        *    A thread that has not yet started is in this state.

        *   

  •     *

  • {@link #RUNNABLE}

        *    A thread executing in the Java virtual machine is in this state.

        *   

  •     *

  • {@link #BLOCKED}

        *    A thread that is blocked waiting for a monitor lock

        *    is in this state.

        *   

  •     *

  • {@link #WAITING}

        *    A thread that is waiting indefinitely for another thread to

        *    perform a particular action is in this state.

        *   

  •     *

  • {@link #TIMED_WAITING}

        *    A thread that is waiting for another thread to perform an action

        *    for up to a specified waiting time is in this state.

        *   

  •     *

  • {@link #TERMINATED}

        *    A thread that has exited is in this state.

        *   

  •     *

    *

    *

    * A thread can be in only one state at a given point in time.

    * These states are virtual machine states which do not reflect

    * any operating system thread states.

    *

    * @since  1.5

    * @see #getState

    */

    public enum State {

        /**

        * Thread state for a thread which has not yet started.

        */

        NEW,

        /**

        * Thread state for a runnable thread.  A thread in the runnable

        * state is executing in the Java virtual machine but it may

        * be waiting for other resources from the operating system

        * such as processor.

        */

        RUNNABLE,

        /**

        * Thread state for a thread blocked waiting for a monitor lock.

        * A thread in the blocked state is waiting for a monitor lock

        * to enter a synchronized block/method or

        * reenter a synchronized block/method after calling

        * {@link Object#wait() Object.wait}.

        */

        BLOCKED,

        /**

        * Thread state for a waiting thread.

        * A thread is in the waiting state due to calling one of the

        * following methods:

        *

            * 

  • {@link Object#wait() Object.wait} with no timeout
  •         * 

  • {@link #join() Thread.join} with no timeout
  •         * 

  • {@link LockSupport#park() LockSupport.park}
  •         *

        *

        *

A thread in the waiting state is waiting for another thread to

        * perform a particular action.

        *

        * For example, a thread that has called Object.wait()

        * on an object is waiting for another thread to call

        * Object.notify() or Object.notifyAll() on

        * that object. A thread that has called Thread.join()

        * is waiting for a specified thread to terminate.

        */

        WAITING,

        /**

        * Thread state for a waiting thread with a specified waiting time.

        * A thread is in the timed waiting state due to calling one of

        * the following methods with a specified positive waiting time:

        *

            * 

  • {@link #sleep Thread.sleep}
  •         * 

  • {@link Object#wait(long) Object.wait} with timeout
  •         * 

  • {@link #join(long) Thread.join} with timeout
  •         * 

  • {@link LockSupport#parkNanos LockSupport.parkNanos}
  •         * 

  • {@link LockSupport#parkUntil LockSupport.parkUntil}
  •         *

        */

        TIMED_WAITING,

        /**

        * Thread state for a terminated thread.

        * The thread has completed execution.

        */

        TERMINATED;

    }

  • {@link #NEW}

    *    A thread that has not yet started is in this state.

    *   

  •   创建后尚未启动的线程处于这种状态

    *

  • {@link #RUNNABLE}

    *    A thread executing in the Java virtual machine is in this state.

    *   

  •   Runable包括了操作系统线程状态的Running和Ready,也就是处于此状态的线程有可能正在执行,也有可能正在等待着CPU为它分配执行时间。

    *

  • {@link #BLOCKED}

    *    A thread that is blocked waiting for a monitor lock

    *    is in this state.

    *   

  •   线程被阻塞了,“阻塞状态”与”等待状态“的区别是:”阻塞状态“在等待着获取到一个排他锁,这个时间将在另外一个线程放弃这个锁的时候发生;而”等待状态“则是在等待一段时间或者唤醒动作的发生。在程序等待进入同步区域的时候,线程将进入这种状态。

    *

  • {@link #WAITING}

    *    A thread that is waiting indefinitely for another thread to

    *    perform a particular action is in this state.

    *   

  •   处于这种状态的线程不会被分配CPU执行时间。

      等待状态又分为无限期等待和有限期等待,WAITING 为无限期等待

      处于无限期等待的线程需要被其他线程显示地唤醒,没有设置Timeout参数的Object.wait()、没有设置Timeout参数的Thread.join()方法都会使线程进入无限期等待状态;

    线程处于WAITING状态的场景。

    调用Object对象的wait方法,但没有指定超时值。

    调用Thread对象的join方法,但没有指定超时值。

    调用LockSupport对象的park方法。

    *

  • {@link #TIMED_WAITING}

    *    A thread that is waiting for another thread to perform an action

    *    for up to a specified waiting time is in this state.

    *   

  •   当处于一个给定的等待时间时候,线程处于这种状态 TIMED_WAITING

      有限期等待状态无须等待被其他线程显示地唤醒,在一定时间之后它们会由系统自动唤醒,Thread.sleep()、设置了Timeout参数的Object.wait()、设置了Timeout参数的Thread.join()方法都会使线程进入有限期等待状态。

    线程处于TIMED_WAITING状态的场景。

    调用Thread.sleep方法。

    调用Object对象的wait方法,指定超时值。

    调用Thread对象的join方法,指定超时值。

    调用LockSupport对象的parkNanos方法。

    调用LockSupport对象的parkUntil方法。

    *

  • {@link #TERMINATED}

    *    A thread that has exited is in this state.

    *   

  •   已终止线程的线程状态,线程已经结束执行。


    线程状态间的切换

    既然有那么多的线程状态,它们之间的状态转换如下图所示


    线程间同步的方法

    线程有4中同步方法,分别为wait()、sleep()、notify()和notifyAll()。

    wait():使线程处于一种等待状态,释放所持有的对象锁。

    sleep():使一个正在运行的线程处于睡眠状态,是一个静态方法,调用它时要捕获InterruptedException异常,不释放对象锁。

    notify():唤醒一个正在等待状态的线程。注意调用此方法时,并不能确切知道唤醒的是哪一个等待状态的线程,是由JVM来决定唤醒哪个线程,不是由线程优先级决定的。

    notifyAll():唤醒所有等待状态的线程,注意并不是给所有唤醒线程一个对象锁,而是让它们竞争。


    Java 创建线程的4种方式 :

    继承Thread类创建多线程

    实现Runnable接口创建多线程

    实现Callable接口通过FutureTask包装器来创建Thread多线程

    使用ExecutorService、Callable、Future实现有返回结果的线程。


    继承Thread类创建多线程

    代码如下:继承Thread类

    package com.dazhi.thread.multithread;

    /**

     * 多线程创建,继承

     * @author dazhi

     */

    public class MyThread extends Thread{

        @Override

        public void run() {

            for (int i=0; i<10; i++) {

                System.out.println(Thread.currentThread().getName() +":"+ i);

            }

        }

        public static void main(String[] args) throws InterruptedException {

            MyThread thread1 = new MyThread();

            MyThread thread2 = new MyThread();

            MyThread thread3 = new MyThread();

            thread1.start();

            thread2.start();

            thread3.start();

        }

    }


    实现Runnable接口创建多线程

    实现Runnable接口

    package com.dazhi.thread.multithread;

    /**

     * 多线程创建, 实现Runnable

     * @author dazhi

     */

    public class MyRunnable implements Runnable {

        @Override

        public void run() {

            for (int i=0; i<10; i++) {

                System.out.println(Thread.currentThread().getName() +":"+ i);

            }

        }

        public static void main(String[] args) {

            MyRunnable myRunnable = new MyRunnable();

            Thread thread1 = new Thread(myRunnable, "thread1");

            Thread thread2 = new Thread(myRunnable, "thread2");

            Thread thread3 = new Thread(myRunnable, "thread3");

            thread1.start();

            thread2.start();

            thread3.start();

        }

    }


    实现Callable接口通过FutureTask包装器来创建Thread多线程

    实现Callable

    package thread.multi;

    import java.util.concurrent.Callable;

    import java.util.concurrent.FutureTask;

    /**

    * Created by szh on 2020/6/15.

    *

    * @author szh

    */

    public class CallableThread implements Callable {

        @Override

        public String call() throws Exception {

            Thread.sleep(10 * 1000);

            return "Just do it";

        }

        public static void main(String[] args) throws Exception {

            CallableThread callableThread = new CallableThread();

            FutureTask stringFuture = new FutureTask(callableThread);

            Thread a = new Thread(stringFuture);

            a.start();

            System.out.println(stringFuture.get());

        }

    }

    // 运行结果

    Just do it

    注意  get 会阻塞线程的运行,直到得到返回结果!!




    使用ExecutorService、Callable、Future实现有返回结果的线程。


    package com.dazhi.thread.multithread;

    import java.util.concurrent.*;

    /**

     * 多线程创建, ExecutorService + Callable + Future

     * @author dazhi

     */

    public class MyExecutors {

        public static void main(String[] args) throws ExecutionException, InterruptedException {

            // 不提倡的方式创建线程池方式。为了方便就这样写了

            ExecutorService executorService = Executors.newFixedThreadPool(5);

            Future submit = executorService.submit(new Callable() {

                @Override

                public Integer call() throws Exception {

                    return 1234;

                }

            });

            executorService.shutdown();

            System.out.println(submit.get());

        }

    }

    // 运行结果

    1234

    Process finished with exit code 0

    // 不提倡创建线程池的原因

    你可能感兴趣的:(Java创建多线程的4种方式 与 线程状态)