java 多线程Thread 详解
1:首先需要理解线程的几种状态
阻塞状态(等待i/o等) — 就绪状态(等待cpu 轮转) —执行状态
2:调用了sleep 方法相当于强制让线程睡觉,暂时不参与cpu 调度,效果上相当于使线程处于阻塞状态
sleep 方法不会释放已经占有的锁资源
3:调用yield 方法相当于让线程主动让出cpu 轮转,即处于就绪状态
4:join 方法是让主线程等待该线程的执行结束,调用该方法会释放已经占有的锁资源
5:interrupt 可以让处于阻塞状态的线程中断。可以让其跑出异常
6:daemon 守护进程,守护进程依赖于创建他的进程,比如在main 中创建一个 daemon 进程,main结束了,该守护进程也就结束了,比如gc 程序,但是用户进程则不一样,main 线程需要等待用户线程的结束。
测试代码比较乱
package concurrent;
/*
* @author: wjf
* @version: 2016年3月27日 上午9:54:26
*/
public class TestThread {
private int count=0;
private Object obj=new Object();
public static void main(String[] args) throws InterruptedException{
System.out.println(Thread.currentThread().getName()+"begin to exec");
/*
* join 可以 让主线程等该该线程执行完
*/
// TestThread test=new TestThread();
MyThread thread1=test.new MyThread();
MyThread thread2=test.new MyThread();
// MyThread[] tt=new MyThread[10];
// for(int i=0;i<10;i++){
// tt[i]=test.new MyThread();
// tt[i].start();
// tt[i].interrupt();
// tt[i].join();
// }
//
//System.out.println(Thread.currentThread().getName()+"begin to wait");
//thread1.join();
//thread2.join();
InterruptedThread it=new InterruptedThread();
it.start();
// it.interrupt();
System.out.println(Thread.currentThread().getName()+"continue to exec");
// while(Thread.activeCount()>1){
// Thread.yield();
// }
}
class MyThread extends Thread{
public void run(){
synchronized(obj){
// System.out.println("count="+count);
System.out.println(Thread.currentThread().getName()+"is running");
for(int i=0;i<100000;i++){
count++;
}
/*
* sleep 方法只是让线程 睡眠,只是让出了cpu 时间,并不会释放 锁,只是处于了就绪状态 ,没有处于阻塞状态
*/
//Thread.sleep(2000);
// test yield
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
System.out.println(Thread.currentThread().getName()+"is done");
// System.out.println("count="+count);
}
}
}
}
class InterruptedThread extends Thread{
public void run(){
try{
System.out.println(Thread.currentThread().getName()+"begin to sleep");
Thread.sleep(1000);
}catch (InterruptedException e){
System.out.println(Thread.currentThread().getName()+"is interrupted");
}finally{
System.out.println(Thread.currentThread().getName()+"exec is done");
}
}
}