Thread 和 Runable 区别

来源:互联网 发布:贪吃飒淘宝小店网址 编辑:程序博客网 时间:2024/05/17 04:57

首先 Thread是类,Runable是接口。

一是写一个类继承自Thread类,然后重写里面的run方法,用start方法启动线程
二是写一个类实现Runnable接口,实现里面的run方法,用new Thread(Runnable target).start()方法来启动

查看源码可以发现 Thread也是实现的Runable

publicclass Thread implements Runnable {

两个都可以实现多线程编程,但是基于java是单继承,所以实现Runable更灵活。并且Runable可以简单的实现变量的线程间共享。


继承Thread

static class MyThread1 extends Thread{     private int ticket=10;    private String threadName;    public MyThread1( String threadName) {        this.threadName = threadName;    }    @Override     public void run() {         for(;ticket>0;ticket--){             System.out.println(threadName+"卖出火车票号:"+ticket);         }     } }
 public static void main(String[] args){        MyThread1 thread1=new MyThread1("从线程1");        MyThread1 thread2=new MyThread1("从线程2");        thread1.start();        thread2.start();//        MyThread2 thread3=new MyThread2("Runable实现类");//        new Thread(thread3).start();//        new Thread(thread3).start();    }

执行结果:
实现Runable 实现共享
static class MyThread2 implements Runnable{     private int ticket=10;     private String threadName;     public MyThread2( String threadName) {         this.threadName = threadName;     }     @Override     public void run() {         for(;ticket>0;ticket--){             System.out.println(threadName+"卖出火车票号:"+ticket);         }     } }
 public static void main(String[] args) {//        MyThread1 thread1=new MyThread1("从线程1");//        MyThread1 thread2=new MyThread1("从线程2");//        thread1.start();//        thread2.start();        MyThread2 thread3 = new MyThread2("Runable实现类");        new Thread(thread3).start();        new Thread(thread3).start();    }
执行结果:

虽然这样可以共享但是这样也存在数据不同步的现象:

两个线程可能读到的ticket不是同步的;

这就需要在实现类里加入同步的代码:

{    synchronized (this){        for (; ticket > 0; ticket--) {            System.out.println(threadName + "卖出火车票号:" + ticket);        }    }}

0 0
原创粉丝点击