java thread 源码
时间: 2023-07-30 13:08:06 浏览: 56
Java中的线程是通过Thread类来实现的,Thread类封装了所有线程相关的方法和属性。下面是Thread类的部分源码:
```java
public class Thread implements Runnable {
//线程状态
private volatile int threadStatus = 0;
private static final int RUNNING = 1;
private static final int SHUTDOWN = -1;
private static final int STOP = -2;
private static final int TIDYING = 2;
private static final int TERMINATED = 3;
//线程优先级
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;
//线程组
private ThreadGroup group;
private Runnable target;
private String name;
private long stackSize;
private long eetop;
//线程ID
private long tid;
//线程本地存储
ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
//线程中断标志
private volatile boolean interrupted = false;
private static final int HIBERNATE = 0;
private static final int WAITING = 1;
private static final int TIMED_WAITING = 2;
private static final int BLOCKED = 3;
private static final int NEW = 0;
//线程锁
private Object parkBlocker;
//线程中断处理
private void handleInterrupt() {
if (this != Thread.currentThread())
throw new RuntimeException("Only the original thread can be interrupted");
if (this.interrupted) {
park();
}
}
//线程休眠
public static void sleep(long millis) throws InterruptedException {
Thread.sleep(millis, 0);
}
//中断线程
public void interrupt() {
if (this != Thread.currentThread())
checkAccess();
synchronized (this) {
interrupted = true;
notifyAll();
}
}
//线程运行方法
@Override
public void run() {
if (target != null) {
target.run();
}
}
}
```
在Thread类中,我们可以看到一些重要的属性和方法,比如:
- threadStatus: 线程状态,用整数表示,包含RUNNING、SHUTDOWN、STOP、TIDYING、TERMINATED五种状态。
- group: 线程所属的线程组。
- target: 线程要执行的任务。
- name: 线程名称。
- stackSize: 线程堆栈大小。
- tid: 线程ID。
- threadLocals: 线程本地存储。
- interrupted: 线程中断标志。
- parkBlocker: 线程锁。
- sleep(): 线程休眠方法。
- interrupt(): 中断线程方法。
- run(): 线程运行方法。
通过这些属性和方法,我们可以使用Java中的线程实现多线程编程。