Java 中使用线程有两种方式:
一、继承 Thread 类
1、创建自定义类并继承 Thread 类。
2、重写 Thread 类中的 run 方法,并编写该线程的业务逻辑代码。
public class MyThread extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
//定义业务逻辑
for(int i = 0;i<10;i++) {
System.out.println("-------------MyThread");
}
}
}
3、使用
public class Test {
public static void main(String[] args) {
//开启两个子线程
MyThread thread1 = new MyThread();
MyThread2 thread2 = new MyThread2();
thread1.start();
thread2.start();
}
}
注意:不能通过 run 方法来调用线程的任务,因为 run 方法调用相当于普通对象的执行,并不会去抢占 CPU 资源。
只有通过start方法才能开启线程,进而去抢占 CPU 资源,当某个线程抢占到 CPU 资源后,会自动调用 run 方法。
二、实现 Runnable 接口
1、创建自定义类并实现 Runnable 接口。
2、实现 run 方法,编写该线程的业务逻辑代码。
public class MyRunnable implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<1000;i++) {
System.out.println("========MyRunnable=======");
}
}
}
3、使用。
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
MyRunnable2 runnable2 = new MyRunnable2();
Thread thread2 = new Thread(runnable2);
thread2.start();
三、两种方式的区别:
1、MyThread,直接在类中重写 run 方法,使用的时候直接实例化 MyThread,使用start()方法开启线程 即可,因为 Thread 内部存在 Runnable。
2、MyRunnbale,在实现类中重写 run 方法,使用的时候需要先创建 Thread 对象,并将 MyRunnable 注入到 Thread 中,之后使用start()方法开启线程。
实际开发中推荐使用第二种方式,可以降低代码耦合度。
四、线程和任务:
线程是去抢占 CPU 资源的,任务是具体执行业务逻辑的,线程内部会包含一个任务,线程启动(start),当抢占到资源之后,任务就开始执行(run)。