zoukankan      html  css  js  c++  java
  • 2018.3.3 多线程中继承Thread 和实现Runnable接口 的比较(通过售票案例来分析)

    多线程中继承Thread 和实现Runnable接口 的比较(通过售票案例来分析)


    通过Thread来实现

    Test.java

    package com.lanqiao.demo4;
    
    public class Test {
    	public static void main(String[] args) {
    		MyThread t1 = new MyThread("张三");
    		
    		MyThread t2 = new MyThread("李四");
    		
    		t1.start();
    		t2.start();
    	}
    }
    
    

    MyThread.java

    
    package com.lanqiao.demo4;
    
    public class MyThread extends Thread {
    	private int ticket = 10;
    
    	public MyThread(String name) {
    		super(name);
    		// TODO Auto-generated constructor stub
    	}
    
    	@Override
    	public void run() {
    		while (true) {
    			if (ticket > 0) {
    				System.out.println(this.getName() + "卖了一张票" + "还剩下"
    						+ (--ticket) + "张票");
    			}
    		}
    	}
    }
    
    
    


    Runnable来实现

    MyRunable.java

    package com.lanqiao.demo5;
    
    public class MyRunable implements Runnable {
    	private int ticket = 10;
    
    	@Override
    	public void run() {
    		while (true) {
    			if (ticket > 0) {
    				System.out.println(Thread.currentThread().getName() + "卖了一张票"
    						+ "还剩下" + (--ticket) + "张票");
    			}
    		}
    	}
    
    }
    
    
    package com.lanqiao.demo5;
    
    public class Test {
    	public static void main(String[] args) {
                    //创建子进程
    		Thread tr1 = new Thread(new MyRunable());
                    //启动进程
    		tr1.start();
    
                    Thread tr2 = new Thread(new MyRunable());
    		tr2.start();
    	}
    }
    
    

    通过比较分析Thread没有实现资源共享(结果显示一共卖了20张,但是我实际只有10张),买票需要实现数据共享,因为我买了一张别人在买的时候会显示少了一张而不是单独的现实少了。在Runnable的例子中,可以这样实现。结果显示与预定的结果一样

  • 相关阅读:
    开源项目cmdbuild-搭建
    开源项目cmdbuild-寄语
    四 上下文切换
    withRouter的作用和一个简单应用
    封装react组件:显示五星评价
    简单使用 Easy Mock-创建线上伪数据
    react中避免内存泄漏的方法
    react中constructor和super的使用
    使用swiper设计移动端轮播图(https://www.swiper.com.cn/)
    vuex模块化练习-购物车
  • 原文地址:https://www.cnblogs.com/qichunlin/p/8497163.html
Copyright © 2011-2022 走看看