温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Thread与runnable在java中有什么不同

发布时间:2020-12-02 16:27:05 来源:亿速云 阅读:134 作者:Leah 栏目:编程语言

Thread与runnable在java中有什么不同 ?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

java中实现多线程的方法有两种:继承Thread类和实现runnable接口

1,继承Thread类,重写父类run()方法

  public class thread1 extends Thread {
 
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println("我是线程"+this.getId());
        }
    }
 
    public static void main(String[] args) {
        thread1 th2 = new thread1();
        thread1 th3 = new thread1();
        th2.run();
        th3.run();
    }
   } 

run()方法只是普通的方法,是顺序执行的,即th2.run()执行完成后才执行th3.run(),这样写只用一个主线程。多线程就失去了意义,所以应该用start()方法来启动线程,start()方法会自动调用run()方法。上述代码改为:

 public class thread1 extends Thread {
    
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println("我是线程"+this.getId());
        }
    }
 
    public static void main(String[] args) {
        thread1 th2 = new thread1();
        thread1 th3 = new thread1();
        th2.start();
        th3.start();
    }
}

通过start()方法启动一个新的线程。这样不管th2.start()调用的run()方法是否执行完,都继续执行th3.start()如果下面有别的代码也同样不需要等待th3.start()执行完成,而继续执行。(输出的线程id是无规则交替输出的) 

2,实现runnable接口

public class thread2 implements Runnable {
 
    public String ThreadName;
    
    public thread2(String tName){
        ThreadName = tName;
    }
    
    
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println(ThreadName);
        }
    }
    
    public static void main(String[] args) {
        thread2 th2 = new thread2("线程A");
        thread2 th3 = new thread2("Thread-B");
        th2.run();
        th3.run();
    }
}

和Thread的run方法一样Runnable的run只是普通方法,在main方法中th3.run()必须等待th2.run()执行完成后才能执行,程序只用一个线程。要多线程的目的,也要通过Thread的start()方法(runnable是没有start方法)。上述代码修改为:

public class thread2 implements Runnable {
 
    public String ThreadName;
    
    public thread2(String tName){
        ThreadName = tName;
    }
    
    
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println(ThreadName);
        }
    }
    
    public static void main(String[] args) {
        thread2 th2 = new thread2("线程A");
        thread2 th3 = new thread2("Thread-B");
        Thread myth2 = new Thread(th2);
        Thread myth3 = new Thread(th3);
        myth2.start();
        myth3.start();
    }
}

 总结:实现java多线程的2种方式,runable是接口,thread是类,runnable只提供一个run方法,建议使用runable实现 java多线程,不管如何,最终都需要通过thread.start()来使线程处于可运行状态。

看完上述内容,你们掌握Thread与runnable在java中有什么不同 的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI