java中线程的状态

线程的状态:一个线程只能有一次NEW状态,和TERMINATED状态
     NEW(新建状态):创建后,启动前。线程就处于该状态

public class Test01 {
	public static void main(String[] args) {
		Thread t = new Thread();
		State s = t.getState();
		System.out.println(s);
	}
}


     RUNNABLE(可运行状态):线程正在执行代码,就处于该状态。

public class Test02 {
	public static void main(String[] args) throws InterruptedException {
		Runnable r = new Runnable() {
			@Override
			public void run() {
				for(;;);
			}
		};
		
		Thread t = new Thread(r);
		t.start();
		Thread.sleep(100);//保证线程已经启动,并开始执行run方法中的代码
		State s = t.getState();
		System.out.println(s);
	}
}


     BLOCKED(阻塞状态):一个线程获取synchronized锁对象失败,就处于该状态

public class Test03 {
	public static void main(String[] args) throws InterruptedException {
		Runnable r = new Runnable() {
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName());
			}
		};
		
		Thread t = new Thread(r);
		t.start();
		Thread.sleep(1000);//保证线程已经启动,并把run方法中的代码执行完毕
		State s = t.getState();
		System.out.println(s);
	}
}


     WAITING(无限等待):一个线程获取Lock锁对象失败,或者调用wait()方法,就处于该状态

public class Test04 {
	public static void main(String[] args) throws InterruptedException {
		Runnable r = new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(50000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		
		Thread t = new Thread(r);
		t.start();
		Thread.sleep(100);//保证线程已经启动,并开始执行run方法中的代码
		State s = t.getState();
		System.out.println(s);
	}
}


     TIMED_WAITING(计时等待状态):线程正执行sleep方法或者wait(long Mills)就处于该状态

public class Test05 {
	public static void main(String[] args) throws InterruptedException {
		Runnable r = new Runnable() {
			@Override
			public void run() {
				synchronized(this) {
					for(;;);
				}
			}
		};
		
		Thread t1 = new Thread(r);
		Thread t2 = new Thread(r);
		t1.start();
		t2.start();
		Thread.sleep(100);//保证两个线程都已经启动,并开始执行run方法
		System.out.println(t1.getState());
		System.out.println(t2.getState());
	}
}



     TERMINATED(消亡状态):线程把任务执行完毕后,就处于该状态。

猜你喜欢

转载自blog.csdn.net/m0_48011056/article/details/125715827