开辟新线程的两种方式

1.创建一个类继承Thread类,重写run()方法

   将一个类声明为Thread的子类。 这个子类应该重写Thread类的方法run()。

  • MyThread 类
public class MyThread extends Thread{
	//重写run()方法
    @Override
    public void run() {
        for (int i=0; i<10; ++i){
            System.out.print(i + "\t");
        }
    }
}
  • Test类
public class Test {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
    }
}
//Output:
// 0	1	2	3	4	5	6	7	8	9	

  在启用线程的使用要调用start()方法才算是开辟新线程,run()方法只是声明了一个任务而已,调用start()方法后使得使得线程进入就绪状态,待该线程抢到CPU时间片后就会执行本线程的run()方法。
  如果单纯的调用run()方法,我们只不过是调用了一个顺序执行的任务而已。


2.实现Runnable接口中的run()方法并传入Thread类的构造器

  创建一个Runnale接口的实现类,或者使用匿名内部类,也可以使用Lambda表达式,将他们传入Thread类的构造器,并调用run()方法。下面的代码展示了这三种方法;

//这是Runnable接口的实现类
class MyThread implements Runnable{
    @Override
    public void run() {
        for (int i=0; i<10; ++i){
            System.out.println(i);
        }
    }
}

public class Test {
    public static void main(String[] args) {
        //1.这里是用将一个Runnable实现类传入Thread构造器
        MyThread myThread = new MyThread();
        Thread thread1 = new Thread(myThread);
        //2.这里是使用匿名内部类实现Runnable接口
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (int i=0; i<10; ++i){
                    System.out.println(i);
                }
            }
        };
        Thread thread2 = new Thread(runnable);
        //3.这里是使用Lambda表达式
        Runnable r = () -> {
            for (int i=0; i<10; ++i){
                System.out.println(i);
            }
        };
        Thread thread3 = new Thread(r);


        thread1.start();
        thread2.start();
        thread3.start();
    }
}

  我个人觉得用Lambda表达式更简单,因为Lambda表达式允许将一段方法当作参数传入构造器:

Thread thread4 = new Thread( () -> {
            for (int i=0; i<10; ++i){
                System.out.println(i);
            }
        });
thread4.start();

  在我之前的博客中粗略的介绍了Lambda表达式

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值