packagecom.ysf;importjava.util.concurrent.TimeUnit;publicclassThreadWay{publicstaticvoidmain(String[] args)throwsInterruptedException{Hello t =newHello();
t.start();TimeUnit.SECONDS.sleep(3L);}staticclassHelloextendsThread{publicvoidrun(){System.out.println("hello");}}}
packagecom.ysf;importjava.util.concurrent.Callable;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.FutureTask;publicclassCallableWay{publicstaticvoidmain(String[] args)throwsExecutionException,InterruptedException{FutureTask<Integer> task =newFutureTask<>(newTst());Thread thread =newThread(task);
thread.start();System.out.println(task.get());}staticclassTstimplementsCallable<Integer>{publicIntegercall()throwsException{int a =0;for(int i=0;i<100;i++){
a +=i;}return a;}}}
线程的状态
NEW状态
packagecom.ysf;publicclassTst01NEWState{publicstaticvoidmain(String[] args){Thread t =newThread(()->{});System.out.println(t.getState());}}
RUNNABLE状态
packagecom.ysf;importjava.util.concurrent.TimeUnit;publicclassTst02RUNNABLEState{publicstaticvoidmain(String[] args)throwsInterruptedException{Thread t =newThread(()->{while(true){}});
t.start();TimeUnit.SECONDS.sleep(20L);System.out.println(t.getState());}}
BLOCKED状态
packagecom.ysf;importjava.util.concurrent.TimeUnit;publicclassTst03BLOCKState{publicstaticvoidmain(String[] args)throwsInterruptedException{Thread t =newThread(()->{// t线程在获取锁的时候阻塞,因为锁已经被主线程拿走了synchronized(Tst03BLOCKState.class){}});// 主线程拿锁后启动t线程synchronized(Tst03BLOCKState.class){
t.start();TimeUnit.SECONDS.sleep(2L);System.out.println(t.getState());}}}