public class T02_HowToCreateThread { static class MyThread extends Thread { @Override public void run() { System.out.println("Hello MyThread!"); } } static class MyRun implements Runnable { @Override public void run() { System.out.println("Hello MyRun!"); } } static class MyCall implements Callable<String> { @Override public String call() { System.out.println("Hello MyCall"); return "success"; } }
public static void main(String[] args) { new MyThread().start(); //第一种 直接经过Thread new Thread(new MyRun()).start(); //第二种 Runnable new Thread(()->{ //第三种 lambda System.out.println("Hello Lambda!"); }).start(); Thread t = new Thread(new FutureTask<String>(new MyCall())); //第四种 t.start(); ExecutorService service = Executors.newCachedThreadPool(); //第五种 使用Executor service.execute(()->{ System.out.println("Hello ThreadPool"); }); service.shutdown(); } }
当线程的run方法执行方法体中的最后一条语句后,并经由执行return语句返回时,或者出现了在方法中没有捕获的异常时,线程将终止。ide
没有能够强制线程终止的方法。然而,interrupt方法能够用来请求终止线程。spa
Java早期版本中,还有一个stop方法,其余线程能够调用它终止线程。可是这个方法已经被弃用了。线程
要肯定一个线程的当前状态,可调用getState方法code