Java中如何创建线程?

1.继承Thread类:

  1. 创建一个类并继承Thread类。
  2. 在子类中重写run()方法,该方法包含了线程的执行代码。
  3. 创建子类的实例,并调用start()方法启动线程。
class MyThread extends Thread {
    public void run() {
        System.out.println("This is a thread running.");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

2.实现Runnable接口:

  1. 创建一个类并实现Runnable接口。
  2. 在实现类中实现run()方法,该方法包含了线程的执行代码。
  3. 创建实现类的实例,并将其作为参数传递给Thread类的构造函数。
  4. 调用Thread类的start()方法启动线程。
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("This is a thread running.");
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

3.简单的实际运用例子,假设我们有一个多线程程序,每个线程负责计算一个数的阶乘,并输出结果。

首先,我们创建一个实现了Runnable接口的类,用于计算阶乘并输出结果:
class FactorialCalculator implements Runnable {
    private int number;

    public FactorialCalculator(int number) {
        this.number = number;
    }

    public void run() {
        long factorial = 1;
        for (int i = 1; i <= number; i++) {
            factorial *= i;
        }
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

然后,在主程序中创建多个线程,并启动它们来计算不同数的阶乘:
public class Main {
    public static void main(String[] args) {
        // 创建多个线程,并为每个线程指定不同的数值
        Thread thread1 = new Thread(new FactorialCalculator(5));
        Thread thread2 = new Thread(new FactorialCalculator(7));
        Thread thread3 = new Thread(new FactorialCalculator(10));

        // 启动线程
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

在这个例子中,我们创建了一个FactorialCalculator类,实现了Runnable接口,并在run()方法中计算了给定数的阶乘。然后,我们在主程序中创建了三个线程,每个线程负责计算一个数的阶乘。最后,通过调用start()方法启动线程。
  • 13
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

霜!!

不错,👆赏!!

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

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

打赏作者

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

抵扣说明:

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

余额充值