Java多线程——第二篇(创建和启动线程)

多线程怎么理解呢?

我个人有一个理解:就像是你们的军队去执行一项任务,就像你的主线程一样。这时候,你派了一个小队去执行侦查敌情的任务。多线程就是这样,主线程执行着任务,这时候,启动一个子线程,说,你去,把这个任务执行了。

这就是我对多线程的理解:新建一个任务。

那么今天我们就来看看怎么派出你的小兵呢?

第一种:

继承Thread类

package thread;

public class MyThread extends Thread{

    @Override
    public void run(){
        System.out.print("myThread");
    }

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

运行结果:

myThread

使用继承方式有什么注意点呢?

  1. Java是单继承的,意味着你不能再继承其他类。

第二种:

实现Runnable接口

package thread;

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.print("MyRunnable");
    }

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

运行结果:

MyRunnable

使用接口实现与继承相比:

  1. Java是多继承的,但是却可以实现多个接口,通过这种方式可以弥补单继承的缺点。
  2. 实际上,Thread类也是实现了 Runnable 接口的。

所以总的来说,实现Runnable的方法 创建线程比 继承Thread类的方法 创建线程 来的更好。

下面说一下,创建线程的时候的注意点:

  1. 实现run()方法,这是为了告诉你的士兵需要做什么,如果你创建一个线程,但是又不告诉他做什么,不是很蠢吗?
  2. 启动线程的方法是 Thread.start()。但是多次调用,会报错,如下:
Exception in thread "main" java.lang.IllegalThreadStateException
	at java.lang.Thread.start(Thread.java:705)
	at thread.MyRunnable.main(MyRunnable.java:9)

重要的一点:

线程虽然创建了,但是,什么时候调用,并不由你的代码顺序决定,例如

package thread;

public class MyThread extends Thread{

    @Override
    public void run(){
        try {
            for (int i = 0 ;i < 10;i++){
                int time = (int) (Math.random()*1000);
                Thread.sleep(time);
                System.out.println("run is " + Thread.currentThread().getName() +i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread myThread = new MyThread();
        myThread.setName("MyThread");
        myThread.start();
        for (int i =0 ;i <10;i++){
            int time = (int) (Math.random()*1000);
            Thread.sleep(time);
            System.out.println("main is "+Thread.currentThread().getName() + i);
        }

    }
}

运行结果:

run is MyThread0
run is MyThread1
main is main0
run is MyThread2
main is main1
main is main2
run is MyThread3
main is main3
main is main4
run is MyThread4
main is main5
run is MyThread5
run is MyThread6
main is main6
run is MyThread7
run is MyThread8
main is main7
run is MyThread9
main is main8
main is main9

可以看到,并不是先运行完 MyThread的run方法,在接下去运行的。

 

好了,该睡觉了,下次再接着bb这些干货。

 

更多内容请关注微信公众号“外里科技

官方公众号外里科技
运营公众号英雄赚
微信wxid_8awklmbh1fzm22
QQ1247408032
开源代码https://gitee.com/B_T/beimi

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值