前言
在Java中,主要提供两种方式实现线程,一个是继承 java.lang.Thread 类,另一个是实现java.lang.Runnable接口。
继承 Thread 类
Thread类是java.lang 包中的一个类,Thread 类中常用的两个构造器如下:
public Thread()
public Thread(String threadName)
创建步骤
① 创建一个继承于Thread类的子类
② 重写Thread类中的 run() 方法
③ 创建Thread 类的子类的对象
④ 通过子类对象调用start去执行 run() 方法
注意
①要想创建多个线程,就需要创建多个子类的对象,即一个子类对象只能启动一个线程
②调用start 方法的时候就是启动当前线程并调用当前线程的run 方法,所以如果直接调用子类对象的run 方法是无法启动新线程的
完整代码
以打印100以内的所有偶数为例
class MyThread extends Thread{
//重写Thread类中的 run
public void run() {
for (int i = 0; i < 100 ; i++){;
if ( i % 2 == 0)
//Thread.currentThread().getName()能显示出当前线程的名字
System.out.println(Thread.currentThread().getName() + i);
}
}
}
public class ThreadTest {
public static void main(String[] args) {
//创建Thread 类的子类 MyThread 类的对象
MyThread t1 = new MyThread();
//4.通过此对象调用start: ①启动当前线程 ②调用当前线程的run()
//如果直接调用 t1.run() 就没有启动新的线程
t1.start();
//以下部分是main线程中的,是和上面t1.start 线程同时进行的
for (int i = 0; i < 100 ; i++){
if ( i % 2 == 0)
//Thread.currentThread().getName()能显示出当前线程的名字
System.out.println(Thread.currentThread().getName() + i + "**********");
}
}
}
实现Runnable 接口
如果程序员需要继承其他类(非Thread类)且还要使用当前类实现多线程,那么就可以通过Runnable 接口来实现。因为Java不支持多继承。
创建步骤
① 创建一个实现了 Runnable 接口的类
② 实现类去实现 Runnable 接口中的抽象方法 run()
③ 创建实现类对象
④ 将此对象作为参数传到Thread 类的构造器中,创建Thread 类的对象
⑤ 通过 Thread 类的对象调用start()方法
完整代码
以打印100以内的所有偶数为例
class MyThread2 implements Runnable{
//实现类去实现 Runnable 接口中的抽象方法:run()
public void run() {
for (int i = 0; i < 100 ; i++){;
if ( i % 2 == 0)
//Thread.currentThread().getName()能显示出当前线程的名字
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
public class ThreadMethod2 {
public static void main(String[] args) {
//创建实现类的对象
MyThread2 myThread2 = new MyThread2();
//将此对象作为参数传递到 Thread 类的构造器中,创建 Thread 类的对象
Thread t1 = new Thread(myThread2);
//通过 Thread 类的对象调用 start()
t1.start() ;
//再启动一个线程,实现同一个run 里的方法只需要再创建一个新的Thread 类的对象
Thread t2 = new Thread(myThread2);
t2.start() ;
}
}