-
继承Thread,并重写父类的run方法
-
public class MyThread extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args){ MyThread my = new MyThread(); my.setName("线程DEMO"); my.start(); } }
-
实现Runable接口,并实现run方法
-
public class MyRunabel implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args){ Thread thread = new Thread(new MyRunabel()); thread.setName("线程DEMO1"); thread.start(); } }
实际开发中,选第2种:java只允许单继承 增加程序的健壮性,代码可以共享,代码跟数据独立
- 使用匿名内部类
-
public class MyThread { public static void main(String[] args){ Thread thread = new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()); } }); thread.setName("aa"); thread.start(); } }
- Lambda表达式
-
public class Lambda { public static void main(String[] args){ new Thread(() ->{ System.out.println(Thread.currentThread().getName()); }).start(); } }
- 线程池
-
public class ThreadPool { public static void main(String[] args){ ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(() ->{ System.out.println(Thread.currentThread().getName()); }); } }
创建线程的方式
最新推荐文章于 2020-05-14 15:06:41 发布