zoukankan      html  css  js  c++  java
  • Thread和Runnable的区别

    【区别】Thread是类,Runnable是接口。

    【联系】Thread类实现了Runnable接口

    【Thread示例】

    class MyThread extends Thread{  
      private int ticket=10;  
      public void run(){  
        for(int i=0;i<20;i++){  
          if(this.ticket>0){  
            System.out.println("卖票:ticket"+this.ticket--);  
          }  
        }  
      }  
    }; 
    
    public class ThreadTicket {  
      public static void main(String[] args) {  
        MyThread mt1=new MyThread();  
        MyThread mt2=new MyThread();  
        MyThread mt3=new MyThread();  
        mt1.start();  
        mt2.start();  
        mt3.start();
      }  
    } 

    start方法 VS run方法

    1. start()用来启动一个新线程,通过Thead类中start()方法来启动的线程处于就绪状态(可运行状态),此时并没有运行,一旦得到CPU时间片,就自动开始执行run()方法。此时不需要等待run()方法执行完也可以继续执行下面的代码。 
    2. run()是在本线程里的,只是线程里的一个函数。如果直接调用run(),就相当于是调用了一个普通函数,必须等待run()方法执行完毕才能执行下面的代码。所以在多线程执行时要使用start()方法而不是run()方法。

    执行结果

    每个线程都各卖了10张,共卖了30张票。但实际只有10张票。每个线程都卖自己的票,没有达到资源共享。

    【Runnable示例】

    class MyThread implements Runnable{  
      private int ticket=10;  
      public void run(){  
        for(int i=0;i<20;i++){  
          if(this.ticket>0){  
            System.out.println("卖票:ticket"+this.ticket--);  
          }  
        }  
      }  
    }  
    
    public class RunnableTicket {  
      public static void main(String[] args) {  
        MyThread mt=new MyThread();  
        new Thread(mt).start(); //通过Thread类的start方法启动多线程
        new Thread(mt).start(); //同一个mt;而在Thread中不可以用同一个实例化对象mt,否则就会出现异常 
        new Thread(mt).start();  
      }  
    }; 

    执行结果:三个线程一共卖了10张票,达到了资源共享。

    【Runnable比Thread的优势】

    1. 避免点继承的局限,一个类可以实现多个接口。
    2. 支持多线程间的资源共享
  • 相关阅读:
    [Codeforces721E]Road to Home
    [Codeforces513E2]Subarray Cuts
    [CodeForces332E]Binary Key
    [HDU4585]Shaolin
    [HDU3726]Graph and Queries
    [BZOJ3224]普通平衡树
    [BZOJ3173]最长上升子序列
    [POJ2985]The k-th Largest Group
    PHP一句话
    体验VIP版本灰鸽子,哈哈,拿到了老师的病毒教程
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/13396184.html
Copyright © 2011-2022 走看看