一. 线程的状态
2.就绪状态(Runnable):
当调用线程对象的start(方法(t.start(;),线程即进入就绪状态。处于就绪状态的线程,只是说明此线程已经做好了准备,随时等待CPU调度执行,并不是说执行了t.start(此线程立即就会执行;
3.运行状态(Running)
4.阻塞状态(Blocked)
阻塞状态又可以分为三种:
a.等待阻塞: 运行状态中的线程执行wait(方法,使本线程进入到等待阻塞状态;
b.同步阻塞: 线程在获取synchronized同步锁失败(因为锁被其它线程所占用,它会进入同步阻塞状态;
c.其他阻塞: 通过调用线程的sleep(或join(或发出了I/O请求时,线程会进入到阻塞状态。当sleep(状态超时、join(等待线程终止或者超时、或者I/O处理完毕时,线程重新转入就绪状态。
5.死亡状态(Dead):线程执行完了或者因异常退出了run(方法,该线程结束生命周期。
二. 实现多线程的4种方式
1. 实现Thread类
1 public class TestThread extends Thread { 2 @Override 3 public void run( { 4 System.out.println("当前线程名" + "->" + Thread.currentThread(.getName(; 5 } 6 } 7 8 public static void main(String[] args { 9 TestThread testThread = new TestThread(; 10 testThread.start(; 11 }
1 public class TestRunnable implements Runnable { 2 @Override 3 public void run( { 4 System.out.println("当前线程名" + "->" + Thread.currentThread(.getName(; 5 } 6 } 7 8 public static void main(String[] args { 9 TestRunnable testRunnable = new TestRunnable(; 10 Thread thread = new Thread(testRunnable; 11 testThread.start(; 12 }
1 public class TestCallable implements Callable<Object> { 2 @Override 3 public Object call( throws Exception { 4 System.out.println("当前线程名" + "->" + Thread.currentThread(.getName(; 5 return null; 6 } 7 } 8 9 public static void main(String[] args { 10 TestCallable testCallable = new TestCallable(; 11 FutureTask futureTask = new FutureTask(testCallable; 12 new Thread(futureTask.start(; 13 }
FutureTask 实现了接口 RunnableFuture,RunnableFuture继承了Runnable接口,所以这种实现等同于方式2实现Runnable接口。