线程的创建方式--(java多线程基础)

来源:互联网 发布:银河历险记3 mac破解 编辑:程序博客网 时间:2024/05/17 02:18

 传统的线程技术中有两种创建线程的方式:一是继承Thread类,并重写run()方法;二是实现Runnable接口,覆盖接口中的run()方法,并把Runnable接口的实现扔给Thread。
 

  • 继承Thread类,重写run方法()
public class Mythread extends Thread {    private volatile int ticket = 10;    @Override    public void run() {        System.out.println("----Thread----");        while (ticket > 0) {            System.out.println(Thread.currentThread() + "  " + ticket);            ticket--;        }    }    public static void main(String[] args) {        Mythread mythread1 = new Mythread();        mythread1.start();        Mythread mythread2 = new Mythread();        mythread2.start();    }}
  • 实现Runnable接口,并实现该接口的run()方法
package 多线程;public class MyRunnable implements Runnable {    private volatile int ticket = 10;    @Override    public void run() {        System.out.println("----Thread----");        while (ticket > 0) {            System.out.println(Thread.currentThread() + "  " + ticket);            ticket--;        }    }    public static void main(String[] args) {        MyRunnable myRunnable = new MyRunnable();        Thread thread = new Thread(myRunnable);        Thread thread2 = new Thread(myRunnable);        thread.start();        thread2.start();    }}

不管是通过继承Thread类还是通过使用Runnable接口来实现多线程的方法,最终还是通过Thread对象的API来控制线程。

两种方式的区别:
通过继承Thread,每个子类间的数据是相互独立的。而实现Runnable的子类的数据是共享的(虽然此时的同步是不安全的,即 ticket 会出现多次相同的情况,但这并不影响数据是共享的)。

采用继承Thread类方式:
(1)优点:编写简单,如果需要访问当前线程,无需使用Thread.currentThread()方法,直接使用this,即可获得当前线程。
(2)缺点:因为线程类已经继承了Thread类,所以不能再继承其他的父类。
采用实现Runnable接口方式:
(1)优点:线程类只是实现了Runable接口,还可以继承其他的类。在这种方式下,可以多个线程共享同一个目标对象,所以非常适合多个相同线程来处理同一份资源的情况,从而可以将CPU代码和数据分开,形成清晰的模型,较好地体现了面向对象的思想。
(2)缺点:编程稍微复杂,如果需要访问当前线程,必须使用Thread.currentThread()方法。


run()方法与start()方法有什么区别(thread.run()与thread.start())
  直接使用run()方法,这会被当成一个普通的函数调用,程序中仍然只有主线程一个线程,也就是说start()方法能够异步地调用run()方法,但是直接调用run()方法确实同步的,因此无法达到多线程的目的。

阅读全文
0 0
原创粉丝点击