当前位置: 移动技术网 > IT编程>开发语言>Java > java创建线程的两种方法区别

java创建线程的两种方法区别

2019年07月22日  | 移动技术网IT编程  | 我要评论

在java中创建一个线程有两种方法:继承thread类和实现runnable接口。

下面通过两个例子来分析两者的区别:

1)继承thread类

public class testthread extends thread {
  int count = 3;

  public testthread(string threadname) {
    super(threadname);
  }

  @override
  public void run() {
    for (int i = 0; i < 10; i++)
      if (count > 0) {
        system.out.println(thread.currentthread().getname() + "--->" + count);
        count--;
      }
  }

  public static void main(string[] args) {
    //new三个线程并启动
    new testthread("线程一").start();
    new testthread("线程二").start();
    new testthread("线程三").start();
  }
}

输出结果:

线程一--->3
线程一--->2
线程一--->1
线程二--->3
线程二--->2
线程二--->1
线程三--->3
线程三--->2
线程三--->1

2)实现runnable接口

同样跟继承thread的代码:

public class testthread implements runnable {
  int count = 3;

  public testthread() {
  }

  @override
  public void run() {
    for (int i = 0; i < 10; i++)
      if (count > 0) {
        system.out.println(thread.currentthread().getname() + "--->" + count);
        count--;
      }
  }

  public static void main(string[] args) {
    testthread tr = new testthread();
    //new三个线程并启动同一个runnable
    new thread(tr, "线程一").start();
    new thread(tr, "线程二").start();
    new thread(tr, "线程三").start();
  }
}

输出结果:

线程一--->3
线程一--->2
线程一--->1 

可以发现两种新建线程的方式最后的输出结果不一样,是因为在继承thread类中,同时创建了三个线程,每个线程都执行一个任务,相当于三个线程分别各自进行三次循环打印log;而在第二种实现runnable接口中是创建三个thread共同去执行tr这个runnable,相当于三个thread共同去执行这一个循环,使得最后count只循环了一次,剩余线程二和线程三都因为使用同一个count导致未能打印出来。

结论:

1)两种创建线程的实现方式不一样,一个通过继承一个通过实现接口,在java中如果已经继承了其他的父类,那么只能实现接口来创建线程。

2)通过上面的例子可以看到继承thread,每个线程都独立拥有一个对象,而实现runnable对象,多个线程共享一个runnable实例。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网