Thread类学习

简介

Thread 类是 Java 中的一个核心类,它代表了一个线程的执行。在 Java 中,每个线程都是由 Thread 类的一个实例表示的。线程是程序执行流的最小单元,它是进程的一个实体,是 CPU 调度和分派的基本单位,它是比进程更小的能独立运行的基本单位。线程自己基本上不拥有系统资源,只拥有一点在运行中必不可少的资源(如程序计数器,一组寄存器和栈),但它可与同属一个进程的其他的线程共享进程所拥有的全部资源。
主要特点:

  • 标识:每个线程都有一个唯一的标识,即线程 ID,可以通过 getId() 方法获取。
  • 状态:线程在其生命周期中可能处于几种不同的状态,如新建(NEW)、可运行(RUNNABLE)、阻塞(BLOCKED)、等待(WAITING)、计时等待(TIMED_WAITING)和终止(TERMINATED)。
  • 优先级:线程有优先级,可以通过 setPriority(int) 方法设置,但高优先级的线程不一定先于低优先级的线程执行。
  • 守护线程:守护线程(daemon thread)是后台线程,用于为其他线程提供服务。当没有非守护线程时,Java 虚拟机将退出。
  • 中断:线程可以被中断,通过 interrupt() 方法实现。被中断的线程可以检查中断状态,并据此作出响应。
  • 线程同步:Thread 类提供了一系列方法来支持线程同步,如 wait(), notify(), notifyAll() 等。

主要方法:

  • start(): 启动线程。
  • run(): 线程执行体,由子类重写。
  • sleep(long millis): 使当前线程暂停执行指定的毫秒数。
  • interrupt(): 中断线程。
  • isInterrupted(): 测试线程是否已经被中断。
  • setPriority(int): 设置线程的优先级。
  • getPriority(): 获取线程的优先级。
  • setName(String): 设置线程的名称。
  • getName(): 获取线程的名称。
  • setDaemon(boolean): 将此线程设置为守护线程或用户线程。
  • isDaemon(): 测试此线程是否为守护线程。
  • join(): 等待该线程终止。
  • wait(), notify(), notifyAll(): 线程之间的通信。

源码

public class Thread implements Runnable {
	//当前线程的名称
	private volatile String name;
	//线程的优先级
	private int priority;
	private Thread threadQ;
	private long eetop;
	//当前线程是否是单步线程
	private boolean single_step;
	//当前线程是否在后台运行
	private boolean daemon = false;
	//Java虚拟机的状态
	private boolean stillborn = false;
	//真正在线程中执行的任务
	private Runnable target;
	//当前线程所在的线程组
	private ThreadGroup group;
	//当前线程的类加载器
	private ClassLoader contextClassLoader;
	//访问控制上下文
	private AccessControlContext inheritedAccessControlContext;
	//为匿名线程生成名称的编号
	private static int threadInitNumber;
	//与此线程相关的ThreadLocal,这个Map维护的是ThreadLocal类
	ThreadLocal.ThreadLocalMap threadLocals = null;
	//与此线程相关的ThreadLocal
	ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
	//当前线程请求的堆栈大小,如果未指定堆栈大小,则会交给JVM来处理
	private long stackSize;
	//线程终止后存在的JVM私有状态
	private long nativeParkEventPointer;
	//线程的id
	private long tid;
	//用于生成线程id
	private static long threadSeqNumber;
	//当前线程的状态,初始化为0,代表当前线程还未启动
	private volatile int threadStatus = 0;
	//由(私有)java.util.concurrent.locks.LockSupport.setBlocker设置
	//使用java.util.concurrent.locks.LockSupport.getBlocker访问
	volatile Object parkBlocker;
	//Interruptible接口中定义了interrupt方法,用来中断指定的线程
	private volatile Interruptible blocker;
	//当前线程的内部锁
	private final Object blockerLock = new Object();
	//线程拥有的最小优先级
	public final static int MIN_PRIORITY = 1;
	//线程拥有的默认优先级
	public final static int NORM_PRIORITY = 5;
	//线程拥有的最大优先级
	public final static int MAX_PRIORITY = 10;
	
	public enum State {
		//初始化状态
		NEW,
		//可运行状态,此时的可运行包括运行中的状态和就绪状态
		RUNNABLE,
		//线程阻塞状态
		BLOCKED,
		//等待状态
		WAITING,
		//超时等待状态
		TIMED_WAITING,
		//线程终止状态
		TERMINATED;
	}

	public Thread() {
		init(null, null, "Thread-" + nextThreadNum(), 0);
	}
	public Thread(Runnable target) {
		init(null, target, "Thread-" + nextThreadNum(), 0);
	}
	public Thread(String name) {
		init(null, null, name, 0);
	}
	public Thread(ThreadGroup group, String name) {
		init(group, null, name, 0);
	}
	public Thread(Runnable target, String name) {
		init(null, target, name, 0);
	}
	public Thread(ThreadGroup group, Runnable target, String name) {
		init(group, target, name, 0);
	}

	private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize) {
        init(g, target, name, stackSize, null, true);
    }
	
	//设置一些基本属性
	private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }

        this.name = name;

        Thread parent = currentThread();
        SecurityManager security = System.getSecurityManager();
        if (g == null) {
            /* Determine if it's an applet or not */

            /* If there is a security manager, ask the security manager
               what to do. */
            if (security != null) {
                g = security.getThreadGroup();
            }

            /* If the security doesn't have a strong opinion of the matter
               use the parent thread group. */
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }

        /* checkAccess regardless of whether or not threadgroup is
           explicitly passed in. */
        g.checkAccess();

        /*
         * Do we have the required permissions?
         */
        if (security != null) {
            if (isCCLOverridden(getClass())) {
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }

        g.addUnstarted();

        this.group = g;
        this.daemon = parent.isDaemon();
        this.priority = parent.getPriority();
        if (security == null || isCCLOverridden(parent.getClass()))
            this.contextClassLoader = parent.getContextClassLoader();
        else
            this.contextClassLoader = parent.contextClassLoader;
        this.inheritedAccessControlContext =
                acc != null ? acc : AccessController.getContext();
        this.target = target;
        setPriority(priority);
        if (inheritThreadLocals && parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;

        /* Set thread ID */
        tid = nextThreadID();
    }

	@Override
	public void run() {
		//直接调用Runnable接口的run()方法不会创建新线程来执行任务,如果需要创建新线程执行任务,则需要调用Thread类的start()方法。
		if (target != null) {
			target.run();
		}
	}

	 public synchronized void start() {
        //线程不是初始化状态,则直接抛出异常
        if (threadStatus != 0)
            throw new IllegalThreadStateException();
        //添加当前启动的线程到线程组
        group.add(this);
        //标记线程是否已经启动
        boolean started = false;
        try {
            //调用本地方法启动线程
            start0();
            //将线程是否启动标记为true
            started = true;
        } finally {
            try {
                //线程未启动成功
                if (!started) {
                    //将线程在线程组里标记为启动失败
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
            }
        }
    }

    private native void start0();

	//本地方法,真正让线程休眠的方法
    public static native void sleep(long millis) throws InterruptedException;
	//调用sleep()方法使线程休眠后,线程不会释放相应的锁。
    public static void sleep(long millis, int nanos)
            throws InterruptedException {
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }
        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                    "nanosecond timeout value out of range");
        }
        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
            millis++;
        }
        //调用本地方法
        sleep(millis);
    }

	public void interrupt() {
        if (this != Thread.currentThread())
            checkAccess();
        synchronized (blockerLock) {
            Interruptible b = blocker;
            if (b != null) {
                interrupt0(); // Just to set the interrupt flag
                b.interrupt(this);
                return;
            }
        }
        //调用本地方法中断线程
        interrupt0();
    }

    private native void interrupt0();
}

示例

public class MyThread extends Thread {  
    @Override  
    public void run() {  
        for (int i = 0; i < 10; i++) {  
            System.out.println("Thread Name: " + Thread.currentThread().getName() + ", " + i);  
        }  
    }  
  
    public static void main(String[] args) {  
        MyThread thread = new MyThread();  
        thread.start();  // 启动线程  
    }  
}

在这个示例中,我们创建了一个名为 MyThread 的新线程,该线程继承自 Thread 类并重写了 run() 方法。在 main 方法中,我们创建了一个 MyThread 对象并调用其 start() 方法来启动线程。当线程启动时,它将执行 run() 方法中的代码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值