创建多线程的几种方式:
// 第一种继承Thread类的方式 static class MyThread extends Thread{ @Override public void run() { // TODO Auto-generated method stub System.out.println("Hello MyThread!"); } } // 第二种实现runnable接口 static class MyRun implements Runnable{ @Override public void run() { // TODO Auto-generated method stub System.out.println("Hello MyRun!"); } } // 第三种实现callable方法 static class MyCall implements Callable<String>{ public String call() { // TODO Auto-generated method stub System.out.println("Helllo MyCall"); return "success"; } }
启动线程的几种方式
// 启动线程的5种方式 new MyThread().start(); new Thread(new MyRun()).start(); new Thread(()-> { System.out.println("Hello Lambda!"); }).start(); Thread t = new Thread(new FutureTask<String>(new MyCall())); t.start(); ExecutorService service = Executors.newCachedThreadPool(); service.execute(()->{ System.out.println("Hello ThreadPool"); }); service.shutdown();