[线程]java的线程状态以及如何新建线程

目录

java Thread中的线程状态定义

线程的状态?

线程的park是什么?

Join和Yield

新建线程

方法1:使用继承extend Thread的方式

方法2:使用runnable

方法3:使用callable

方法4:使用线程池


java Thread中的线程状态定义

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:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * 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:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;
    }

线程的状态?

这个是Thread 类源码中的状态, 也可以说是java中的线程的状态

NEW :构造了thread实例,但是还没有start

RUNNABLE:正在运行或者正等待被cpu执行

BLOCKED :线程调用synchronized关键字等待获取monitor锁

WAITING : 线程调用了无超时的wait、join、park方法

TIMED_WAITING 

TERMINATED (英文释义:停止,结束,终止)

这个相当于操作系统的线程状态,java线程状态有6种:新建、运行、阻塞、无限等待、限期等待、结束。

其中:running状态由于只是分配了CPU时间片时才算running,所以一般统称为runnable

因为网上很多资料都讲线程是这样的:其实是进程的状态划分是这样的:五个状态

线程的park是什么?

 使用 JAVA 进行多道编程时,除了通过 wait/notify 对线程进行阻塞/唤醒外,我们还可以使用 LockSupport 工具类来阻塞和唤醒线程。

 结果:

thread start!
 from main thread
thread weakup!

相当于阻塞和唤醒线程

park/unpark 没有基于对象锁的上层判断逻辑,更直接的通过系统调用来操作线程,当然在系统调用之上还是做了一些小封装。与 wait/notify 相比:

  1. park不需要获取某个对象的锁
  2. 因为中断的时候park不会抛出InterruptedException异常,所以需要在park之后自行判断中断状态,然后做额外的处理。就像 sleep ,notify 唤醒后,jvm 会帮助我们检查一次是否有 interrupt 信号,将检查 interrupt 信号的逻辑放在阻塞线程的逻辑之后,一旦被唤醒,首先执行检查 interrupt 信号的逻辑,检查完后退出 sleep/wait 方法,程序继续向下执行。而 park / unpark 并没有提供类似的机制,如果需要我们应自己在 park 方法后加入检查 interrupt 信号的逻辑。
  3. 想想happen-before原则中有一条,同一个锁的unlock操作happen-before此锁的lock操作。park/unpark 并没有涉及到锁操作,但我们确实有保证在一对操作中, park 发生在 unpark 之前的需求,否则可能会造成程序的死锁。关于这点 park/unpark 通过为线程附加状态位满足了我们的需求:unpark调用时,如果当前线程还未进入park,则将许可设置为true;park调用时,判断许可是否为true,如果是true,则 park 不阻塞线程,程序继续往下执行;如果是false,则阻塞线程。所以只要我们的 park/unpark 成对出现,无论执行顺序如何,都不会因此造成死锁

转自:https://www.cnblogs.com/niuyourou/p/12715775.html

写得挺好

Join和Yield

Join是Thread类成员方法,该方法作用是当前线程等待某个线程结束后再继续执行后续代码。

Yield是Thread类静态方法,该方法作用是让当前线程放弃cpu,并等待cpu重新调度(当前线程可能再次获得cpu)。通俗点的说法是给其它线程一个机会,让大家回到同一起跑线,至于谁被cpu选中,看个人造化。

新建线程

方法1:使用继承extend Thread的方式

package com.dk.learndemo.thread;

/**
 * @desc: NewThreadExtend
 * @author: pmdream
 * @date: 2021/8/23 2:39 下午
 */
public class NewThreadExtend extends Thread {

    @Override
    public void run() {
        func();
    }

    public void func(){
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "打印" + i);
        }
    }

    public static void main(String[] args) {
        NewThreadExtend thread1 = new NewThreadExtend();
        thread1.start();
    }
}

方法2:使用runnable

// 因为java是单继承的,所以用实现接口方式还是比较好的

package com.dk.learndemo.thread;

/**
 * @desc: 实现Runnable接口 直接实现Runnable接口(避免单继承的局限性,方便共享资源,推荐使用)
 * @author: pmdream
 * @date: 2021/8/23 2:39 下午
 */
public class NewThreadRunnable implements Runnable {
    /**
     * 实现Runnable接口的run方法,这个方法称为线程执行体
     */
    @Override
    public void run() {
        func();
    }

    private void func() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "打印" + i);
        }
    }

    public static void main(String[] args) {
        NewThreadRunnable thread2 = new NewThreadRunnable();
        new Thread(thread2).start();
    }
}

方法3:使用callable

package com.dk.learndemo.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @desc: NewThreadCallable
 *        支持泛型的返回值
 * @author: pmdream
 * @date: 2021/8/23 2:39 下午
 */
public class NewThreadCallable implements Callable<String> {

    private int ticket = 5;

    /**
     * callable 需要实现这个方法;
     * 实现的call()方法相比run()方法,可以返回值
     *
     */
    @Override
    public String call() throws Exception {
        func();
        return "call方法的返回值";
    }

    public void func() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "打印" + i);
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<String> callableThread = new NewThreadCallable();
        FutureTask<String> task = new FutureTask<>(callableThread);
        new Thread(task).start();
        // FutureTask类,获取返回结果
        // 这个主要打印的是: call方法的返回值
        System.out.println(task.get());
    }
}

方法4:使用线程池

// 创建线程池源码和原理还得好好看看

package com.dk.learndemo.thread;

/**
 * @desc: ThreadPoolUtils
 * @author: pmdream
 * @date: 2021/8/23 3:24 下午
 */
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolUtils {

    private static ExecutorService COMMON_POOL = new ThreadPoolExecutor(10, 10, 60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());

    private static final Map<String, ThreadPoolExecutor> threadPoolMap;

    static {
        threadPoolMap = new HashMap<>();
        threadPoolMap.put("commonThreadPool", (ThreadPoolExecutor) COMMON_POOL);
    }

    /**
     * 通用线程池
     */
    public static ExecutorService getCommonPool() {
        return COMMON_POOL;
    }

    /**
     * 获取线程池map
     */
    public static Map<String, ThreadPoolExecutor> getThreadPoolMap() {
        return threadPoolMap;
    }

    public static void main(String[] args) {
        Map<String, ThreadPoolExecutor> map =  ThreadPoolUtils.getThreadPoolMap();
        System.out.println();
    }
}

参考文章:

https://www.jianshu.com/p/6aff628d05fb

 https://www.cnblogs.com/niuyourou/p/12715775.html

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值