线程共包括一下5种状态java
//工具的Java线程状态, 初始化表示线程'还没有启动'
private volatile int threadStatus = 0;
//这个线程的组
private ThreadGroup group;
public synchronized void start() {
//若是线程不是"就绪状态",则抛出异常!
if (threadStatus != 0)
throw new IllegalThreadStateException();
//将线程添加到ThreadGroup中
//通知组该线程即将启动,这样它就能够添加到组的线程列表中,而且该组的未启动计数能够递减
group.add(this);
boolean started = false;
try {
//经过该方法启动线程
start0();
//设置标记
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 */
}
}
}
复制代码
start()其实是经过本地方法start0()启动线程的。而start0()会新运行一个线程,新线程会调用run()方法。安全
/* What will be run. */
private Runnable target;
public void run() {
if (target != null) {
target.run();
}
}
复制代码
target是一个Runnable对象。run()就是直接调用Thread线程的Runnable成员的run()方法,并不会新建一个线程。bash
“synchronized方法”是用synchronized修饰方法,而 “synchronized代码块”则是用synchronized修饰代码块。多线程
@Override
public void run() {
while (true) {
try {
// 执行任务...
} catch (InterruptedException ie) {
// InterruptedException在while(true)循环体内。
// 当线程产生了InterruptedException异常时,while(true)仍能继续运行!须要手动退出
break;
}
}
}
复制代码
// Demo1.java的源码
class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
@Override
public void run() {
try {
int i=0;
while (!isInterrupted()) {
Thread.sleep(100); // 休眠100ms
i++;
System.out.println(Thread.currentThread().getName()+" ("+this.getState()+") loop " + i);
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() +" ("+this.getState()+") catch InterruptedException.");
}
}
}
public class Demo1 {
public static void main(String[] args) {
try {
Thread t1 = new MyThread("t1"); // 新建“线程t1”
System.out.println(t1.getName() +" ("+t1.getState()+") is new.");
t1.start(); // 启动“线程t1”
System.out.println(t1.getName() +" ("+t1.getState()+") is started.");
// 主线程休眠300ms,而后主线程给t1发“中断”指令。
Thread.sleep(300);
t1.interrupt();
System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted.");
// 主线程休眠300ms,而后查看t1的状态。
Thread.sleep(300);
System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted now.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
复制代码
//设置该线程的优先级
thread.setPriority(1);
复制代码