如何创建多线程
1.继承 Thread类,并重写run()方法:
public class Thread001 extends Thread{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"我是子线程"); } public static void main(String[] args) { System.out.println(Thread.currentThread().getName()+"我是主线程"); new Thread001().start(); } }
2.实现Runnable接口,并重写run()方法:
public class Thread002 implements Runnable{ public void run() { System.out.println(Thread.currentThread().getName()+"我是子线程1"); } public static void main(String[] args) { new Thread(new Thread002()).start(); } }
3.使用内部类:
public class Thread0022{ public static void main(String[] args) { //写法1 new Thread(new Runnable() { public void run() { System.out.println(Thread.currentThread().getName()+"我是子线程1"); } }).start(); //写法二:使用lambda表达式 new Thread(() -> System.out.println(Thread.currentThread().getName()+"我是子线程2")).start(); } }
4.可以带返回结果的线程Callable:
但是这种方式的话因为要等待子线程返回结果,所以你它的用时跟直接一个方法走没啥区别。
public class MyCallback implements Callable<String> { @Override public String call() throws Exception { try{ Thread.sleep(3000); }catch (Exception e){} return "子线程返回了!"; } public static void main(String[] args) throws ExecutionException, InterruptedException { System.out.println("主线程开始了!"); FutureTask<String> futureTask = new FutureTask<>(new MyCallback()); new Thread(futureTask).start(); System.out.println("这是---》》》"+futureTask.get()); System.out.println("主线程结束了!"); } }
5.线程池:
public class Thread003 { public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(new Runnable() { @Override public void run() { System.out.println("我是"+Thread.currentThread().getName()+"线程池1"); } }); //写法2:使用lambda表达式 executorService.execute(() -> System.out.println("我是"+Thread.currentThread().getName()+"线程池2")); } }