一、继承Thread类
-
语法格式
public class MyThread extends Thread { @Override public void run() { } }
-
步骤
-
写一个类直接继承Thread类
-
重写run方法。该run()方法的方法体就代表了线程需要完成的任务。
-
创建Thread子类的实例。
-
调用线程对象的start()方法来启动该线程。
-
-
举个列子
public class ThreadExample { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); } }
二、实现Runnable接口(推荐)
-
步骤
-
定义Runnable的实现类,重写run()方法。
-
创建Runnable实现类的实例,并以此作为Thread的target来创建对象,该对象才是真正的线程对象。
-
-
语法格式
public class MyRunnable implements Runnable{ @Override public void run() { } }
-
举个栗子
public class MyRunnable implements Runnable{ @Override public void run() { System.out.println("这个是实现Runnable"); } } public class ThreadExample { public static void main(String[] args) { // 第一步 Runnable runable = new MyRunnable(); //第二步 Thread thread = new Thread(runable); // 第三步 thread.start(); } }
-
注意
**只有调用了start()方法,才会表现出多线程的特性,不同线程的run()方法里面的代码交替执行。**如果只是调用run()方法,那么代码还是同步执行的,必须等待一个线程的run()方法里面的代码全部执行完毕之后,另外一个线程才可以执行其run()方法里面的代码。
三、匿名内部类实现
-
方式一
public class AnonThread { public static void main(String[] args) { anonThread(); } public static void anonThread() { Thread t = new Thread() { @Override public void run() { super.run(); System.out.println("白天么么哒! 晚上xxx"); } }; t.start(); } }
-
方式二
public class AnonThread { public static void main(String[] args) { anonRunnable(); } public static void anonRunnable() { Thread t = new Thread(new Runnable() { @Override public void run() { System.out.println("自古多情空余恨, 总是套路得人心!"); } }); t.start(); /** * 简写方式 1.8以上的版本还可以使用lambda表达式 */ new Thread(() -> System.out.println("我爱撸代码")).start(); } }
四、特殊线程主线程
-
说明
JVM调用程序main()所产生的线程
-
举个栗子
public class MainThreadExample { public static void main(String[] args) { System.out.println(Thread.currentThread().getName()); // main } }
五、使用Runnable的优点
- 适合多个相同的程序代码的线程去处理同一个资源
- 可以避免java中的单继承的限制
- 增加程序的健壮性,代码可以被多个线程共享,代码和数据独立
- 线程池只能放入实现Runable或callable类线程,不能直接放入继承Thread的类