线程
,在网络或多用户环境下,一个服务器通常需要接收大量且不确定数量用户的并发请求,为每一个请求都创建一个进程显然是行不通的,——无论是从系统资源开销方面或是响应用户请求的效率方面来看。因此,操作系统中线程的概念便被引进了。线程,是进程的一部分,一个没有线程的进程可以被看作是单线程的。线程有时又被称为轻权进程或轻量级进程,也是 CPU 调度的一个基本单位。
public class FirstMethod extends Thread {
@Override
public void run() {
super.run();
}
}
FirstMethod firstMethod = new FirstMethod();
firstMethod.start();
public class SecondMethod implements Runnable{
@Override
public void run() {
}
}
SecondMethod secondMethod=new SecondMethod();
new Thread(secondMethod).start();
public class BugThread extends Thread {
private volatile int bugNumber = 5;
@Override
public void run() {
for (int i = 0; i < bugNumber; i++) {
System.out.println("bugNumber--->" + bugNumber--);
}
}
}
public class Main {
public static void main(String[] args) {
new BugThread().start();
new BugThread().start();
new BugThread().start();
}
}
public class BugRunnable implements Runnable {
private volatile int bugNumber = 15;
@Override
public void run() {
while (bugNumber > 0)
System.out.println(Thread.currentThread().getName() + "-----" + bugNumber--);
}
}
public static void main(String[] args) {
BugRunnable bugRunnable = new BugRunnable();
new Thread(bugRunnable).start();
new Thread(bugRunnable).start();
new Thread(bugRunnable).start();
}
private volatile char name[];//线程名称的字节数组
private int priority;//线程优先级
private boolean single_step; //线程是否单步
private boolean daemon = false; //是否是守护线程
private boolean stillborn = false; //JVM state
private Runnable target; //从构造方法传过来的Runnable
private ThreadGroup group; //线程组
private ClassLoader contextClassLoader; //类加载器
private static int threadInitNumber; //线程编号
private volatile int threadStatus = 0; //初始状态
public final static int MIN_PRIORITY = 1; //最低优先级
public final static int NORM_PRIORITY = 5; //默认优先级
public final static int MAX_PRIORITY = 10; //最高优先级
线程状态
publicenum State {
//Thread state for a thread which has not yet started.
NEW,
//Thread state for a runnable thread.
RUNNABLE,
//Thread state for a thread blocked waiting for a monitor lock.
BLOCKED,
// Thread state for a waiting thread.
WAITING,
//Thread state for a waiting thread with a specified waiting time.
TIMED_WAITING,
//Thread state for a terminated thread
TERMINATED;
}
/**
* Initializes a Thread.
*
* @param g //线程组
* @param target //构造方法传过来的Runnable
* @param name //线程名称
* @param stackSize //给线程分配的栈的深度
* @param acc //上下文加载器
*/privatevoidinit(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc){
if (name == null) {
thrownew NullPointerException("name cannot be null");
}
this.name = name.toCharArray();
Thread parent = currentThread();
SecurityManager security = System.getSecurityManager();
//判断线程组参数是否为空if (g == null) {
if (security != null) {
g = security.getThreadGroup();
}
if (g == null) {
g = parent.getThreadGroup();
}
}
g.checkAccess();
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();
elsethis.contextClassLoader = parent.contextClassLoader;
this.inheritedAccessControlContext =
acc != null ? acc : AccessController.getContext();
this.target = target;//初始化target
setPriority(priority);//设置优先级if (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();//设置线程ID
}
start方法
publicsynchronizedvoidstart(){
if (threadStatus != 0)//判断线程是否准备好
group.add(this);//将启动的线程线程组boolean started = false;
try {
start0();//本地方法,JVM调用target的run方法
started = true;//更改启动标志
} finally {
try {
if (!started)
group.threadStartFailed(this);//通知线程组启动失败
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
@Overridepublicvoidrun(){
if (target != null) {
target.run();
}
}
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);//调用本地方法
}
publicfinalsynchronizedvoidjoin(long millis)throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
thrownew IllegalArgumentException("timeout value is negative");
}
if