• Runnable与Thread区别


    简述

    Runnable是接口,Thread是类且实现Runnable接口

    Thread线程是独立的不共享资源

    Runnable是资源共享

    在使用Runnable定义的子类中没有start()方法,只有Thread类中才有。

    Thread类,有一个构造方法:public Thread(Runnable targer)

    此构造方法接受Runnable的子类实例,也就是说可以通过Thread类来启动Runnable实现的多线程。

    public Thread(Runnable runnable)  
    {  
        daemon = false;  
        stillborn = false;  
        threadLocals = null;  
        inheritableThreadLocals = null;  
        threadStatus = 0;  
        blockerLock = new Object();  
        init(null, runnable, (new StringBuilder()).append("Thread-").append(nextThreadNum()).toString(), 0L);  
    }  
    

      

    使用情况

    在程序开发中只要是多线程肯定永远以实现Runnable接口为主。

    实现Runnable接口相比继承Thread类有如下好处:
    1、避免继承的局限,一个类可以继承多个接口。
    2、适合于资源的共享。

    举例

    三个网友分别抢10张优惠券

    继承Thread

    /**
     * MyThreadWithExtends
     * 
     * @author Stephen
     * @time 2020-7-1 17:59:02
     */
    public class MyThreadWithExtends extends Thread {
    
    	private int number = 10;
    
    	@Override
    	public void run() {
    
    		for (int i = 0; i <= 100; i++) {
    			if (number > 0) {
    				number--;//优惠卷减一
    				System.out.println(Thread.currentThread().getName() + "顾客抢到手,剩余优惠券:" + number);
    			}
    		}
    	}
    
    	public static void main(String[] args) {
    		MyThreadWithExtends thread1 = new MyThreadWithExtends();
    		MyThreadWithExtends thread2 = new MyThreadWithExtends();
    		MyThreadWithExtends thread3 = new MyThreadWithExtends();
    
    		thread1.start();
    		thread2.start();
    		thread3.start();
    
    		// 每个线程都独立,不共享资源,每个线程都抢了10张,总共抢了30张。如果真抢,就有问题了。
    	}
    
    }
    

     

    运行结果

    /**
     * MyThreadWithExtends
     * 
     * @author Stephen
     * @time 2020-7-1 17:59:59
     */
    public class MyThreadWithExtends  implements Runnable {
    
    	private int number = 10;
    
    	@Override
    	public void run() {
    
    		for (int i = 0; i <= 100; i++) {
    			if (number > 0) {
    				number--;//优惠卷减一
    				System.out.println(Thread.currentThread().getName() + "顾客抢到手,剩余优惠券:" + number);
    			}
    		}
    	}
    
    	public static void main(String[] args) {
    		MyThreadWithExtends myClass = new MyThreadWithExtends();
    		Thread thread1 = new Thread(myClass,"网友1");
    		Thread thread2 = new Thread(myClass,"网友2");
    		Thread thread3 = new Thread(myClass,"网友3");
    
    		thread1.start();
    		thread2.start();
    		thread3.start();
    	}
    
    }
    

      

  • 相关阅读:
    微博短地址识别正则表达式
    VM 虚拟机, linux mount windows的共享目录,php报错:Fatal error: Unknown: Failed opening required
    新贵 轻雅 100 数字键 numlock问题
    [转]人大常委会委员:文理分科降低民族整体素质
    NTFS变RAW后的修复
    西门子plc视频教程
    ProE 工程图教程系列3 Pro/E消息区域中错误、警告消息的处理
    奥运会上同时升起三面五星红旗
    亦歌 在线听歌网站
    [转]国内外常用钢号对照表
  • 原文地址:https://www.cnblogs.com/dzcici/p/13220817.html
Copyright © 2020-2023  润新知