Java创建多线程的两种方法

前言

在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() ;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不怕娜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值