Thread 和 Runable 区别

首先 Thread是类,Runable是接口。

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

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

public
class 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
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值