java并发编程之Thread和Runnable(二)

1.在java中,创建线程一般只有两种方法;1)继承Thread;2)实现Runnable接口;

2.继承Thread类:

class MyThread extends Thread{
    private String name;
    public MyThread(String name){
        this.name = name;
    }
    //继承Thread类的话,必须重写run方法,在run方法中定义需要执行的任务
    @Override
    public void run() {
        System.out.println("name:"+name+" 子线程ID:"+Thread.currentThread().getId());
    }
}

public class test {
    public static void main(String[] args)  {
        MyThread thread1 = new MyThread("thread1");
        thread1.start();
    }
}

3.注意点 runstart使用误区:

(1)线程启动要用start()方法,只有它才能创建一个新的线程来执行定义的任务

(2)run方法只是定义了需要执行的任务,如果调用run方法,即相当于在主线程中执行run方法,跟普通的方法调用没有任何区别

4.结果对比:

public class test {
    public static void main(String[] args)  {
    	System.out.println("主线程ID:"+Thread.currentThread().getId());
        MyThread thread = new MyThread("thread");
        thread.start();
        thread.run();
        MyThread thread2 = new MyThread("thread2");
        thread2.run();
    }
}

结论:1)调用了run()方法的子线程id与主线程id一致;不会创建新的线程,与普通方法调用一致。

            2)调用了start()方法创建了新的线程。

5.实现Runnable接口:

public class Test {
    public static void main(String[] args)  {
        System.out.println("主线程ID:"+Thread.currentThread().getId());
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}
 
class MyRunnable implements Runnable{
    public MyRunnable() {
         
    }
    @Override
    public void run() {
        System.out.println("子线程ID:"+Thread.currentThread().getId());
    }
}

发现:1)这种方式必须将Runnable作为Thread类的参数,然后通过Thread的start方法来创建一个新线程来执行该子任务。

2)源代码中,Thread类是实现了Runnable接口方法的。

6.Thread与Runnable区别:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值