java线程概述

Java线程

本文基于对java中线程的简单剖析,如有不足的地方,欢迎大家评论区指正!

概述

java线程Thread是Java语言和JVM提供的一种多线程技术,可以使得开发人员可以省去操作系统底层的线程实现细节来完成多线程技术的使用

创建线程的四种方式

继承Thread

class MyThread extends Thread{

	@override
	public void run(){
		
	}
}

new MyThread().start();

不足:Java是单继承,如果当前类还需要拓展继承其它父类则无法进行

实现Runnable接口

class MyRunnable implements Runnable{
	@Override
	public void run(){
		
	}
}

// 启动线程

new Thread(new MyRunnable(),"your thread name").start();

优势:接口的方式实现,可扩展性强(Java支持多实现)

实现Callable接口

class MyCallable<T> implements Callable<T>{
	@Override
	public T call() throw Exception{
		return T;
	}
}

// 启动线程
FutureTask futureTask = new FutureTask(new MyCallable());

new Thread(futureTask,"").start();

优势:支持线程执行返回值的获取、异常的抛出

线程池

概述:

使用线程池去创建线程,可以让线程得到复用,减少CPU资源的消耗(线程上下文的切换)

注意:线程池的使用需要考虑参数的自定义,否则会带来难以预计的问题,例如:无界阻塞队列将无限的接受任务而可能导致OOM

// 基于Executors

// 自定义
ExecutorService executor = new ThreadPoolExecutor(
	int coreThreadSize,// 活跃线程的数量
	int maxThreadSize,// 最大线程的数量,
	long expireTime, // 超过活跃线程数量的其它线程的最大空闲时间
	TimeUnit timeUnit, // 最大空闲时间的时间单位
	BlockingQueue<Runnable> workQueue, // 阻塞队列,接受超过活跃线程数的任务
	ThreadFactory thradFactor, // 线程工厂,如何创建线程(多用于自定义ThreadGroup、ThreadName)
	RejectedExecutionHandler rejectHandler // 拒绝策略:线程池无法处理请求的线程的失败策略
);

对比

  1. 线程池的方式更多可用,但是需要确认参数的配置。企业中用的比较多
  2. 实现Callable接口的方式一般结合线程池使用,用于返回值的获取及异常的处理
  3. 实现Runnable接口的方式,同上。只不过是没有返回值和异常的处理
  4. 继承Thread的方式,感觉很少直接使用

线程的状态

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;
}

图例

新建
运行
阻塞
等待
超时等待
终止

常用方法

start

加载线程所需环境并调用navite 方法创建线程

sleep

不释放锁、处理器资源休眠指定时间

join

插入到指定线程前,必须等当前线程完成,后续的线程才可以继续进行,示例:

public class JoinTest {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("main start");
        Thread threadA = new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+"--> infoA");
            System.out.println("====sleep start====");
            System.out.println(Thread.activeCount());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("当前线程的状态和id:"+Thread.currentThread().getState()+"-"+Thread.currentThread().getId()+"-"+Thread.currentThread().getThreadGroup().getName());
            System.out.println("====sleep end====");
        }, "A");
        threadA.start();
        // 休息200ms然后中断threadA
//        Thread.sleep(50);
//        threadA.interrupt();
        threadA.join();
        System.out.println(Thread.activeCount());
        System.out.println("当前线程的状态和id:"+Thread.currentThread().getState()+"-"+Thread.currentThread().getId()+"-"+Thread.currentThread().getThreadGroup().getName());

        System.out.println("main end");
    }
}

输出

main start
A--> infoA
====sleep start====
3
当前线程的状态和id:RUNNABLE-12-main
====sleep end====
2
当前线程的状态和id:RUNNABLE-1-main
main end

activeCount

获取JVM运行线程的数量

main方法启动就包含:main线程和gc线程

interrupt

中断线程:论如何优雅的中断线程【😂】

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值