1继承Thread方法
2实现Runnable接口
3用Lambda表达式
4 实现Callable接口,可以通过泛型指定返回数据类型,返回数据
5 利用线程池
public class HowToCrateThread { static class MyThread extends Thread { @Override public void run() { System.out.println("Hello Thread!"); } } static class MyRun implements Runnable { @Override public void run() { System.out.println("Hello Runnable!"); } } static class MyCall implements Callable<String> { @Override public String call() throws Exception { System.out.println("Hello Callable!"); return "SUCCESS"; } } public static void main(String[] args) throws ExecutionException, InterruptedException { // 方法1继承Thread方法 new MyThread().start(); // 方法2实现Runnable new Thread(new MyRun()).start(); // 方法3用流Lambda new Thread(()-> {System.out.println("Hello Lambda!"); }).start(); // 方法4 实现Callable接口,可以通过泛型指定返回数据类型,返回数据 Thread thread = new Thread(new FutureTask<String>(new MyCall())); thread.start(); // 方法5 利用线程池 ExecutorService service = Executors.newCachedThreadPool(); service.execute(()->{ System.out.println("Hello ThreadPool"); }); Future<String> future = service.submit(new MyCall()); String s = future.get(); System.out.println(s); service.shutdown(); } /** * 输出 * Hello Thread! * Hello Runnable! * Hello Lambda! * Hello Callable! * Hello ThreadPool * Hello Callable! * SUCCESS */ } |