创建多线程的两种方式

/*
//方法一:
        1.创建一个类继承Thread类
        2.重写run方法
        3.启动.start()


class Demo extends Thread{
    private String name;
    Demo(String name){
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0;i < 100;i++) {
            System.out.println(name+i+"..."+Thread.currentThread().getName());
        }
    }

}

public class ThreadTest {
    public static void main(String[] args) {
        Demo d1 = new Demo("小强");
        Demo d2 = new Demo("旺财");
        Demo d3 = new Demo("san");
        d3.start();
        d2.start();
        d1.run();
    }
}
*/

/*

方法二:
        1.创建类实现Runnable接口
        2.实现run()方法,将线程任务定义到run方法中
        3.创建Thread对象,只有创建Thread类的对象才可以创建线程
        4.将Runnable接口的子类对象作为参数传给Thread类的构造函数.
           因为线程任务已被封装到Runnable接口的run方法中,而这个run方法所属于Runnable接口的子类对象
           所以将这个子类对象作为参数传递给Thread的构造函数,这样,线程对象创建时就可以明确要运行的线程任务.
        5.调用Thread类的start()方法

好处:
    实现接口避免单继承的局限性,比较常用
    降低线程对象和线程任务的耦合性



简易源代码:
class Thread{
    private Runnable target;
    Thread(Runnable target){
        this.target = target;
    }
    public void run(){
        if(target != null){
            target.run();
        }
    }
    public void start(){
        run();
    }
}

Runnable d = new Demo();
Thread t = new Thread(d);
t.start();
 */
class Demo implements Runnable{
    private String name;
    Demo(String name){
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0;i < 100;i++) {
            System.out.println(name + i + "..." + Thread.currentThread().getName());
        }
    }
}

public class ThreadTest{
    public static void main(String[] args) {
        Demo d1 = new Demo("小强");
        Demo d2 = new Demo("旺财");
        Thread t1 = new Thread(d1);
        Thread t2 = new Thread(d2);

        t1.start();
        t2.start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值