zoukankan      html  css  js  c++  java
  • Java 多线程实现方式二:实现 Runnable 接口

    由于java是单继承,很多时候为了实现多线程 通过继承 Thread 类后,就不能再继承其他类了。为了方便可以通过实现 Runnable 接口来实现,和Tread 类似需要重写run 方法。
    下面通过模拟12306 黄牛抢票来简单应用:

    public class Web12306 implements Runnable{
    	//票数
    	private int ticketNums = 99;
    	
    	@Override
    	public void run() {
    		while(true) {
    			if(ticketNums<0) {
    				break;
    			}
    			try {
    				Thread.sleep(200);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			System.out.println(Thread.currentThread().getName()+"-->"+ticketNums--);
    		}
    	}
    	public static void main(String[] args) {
    		//一份资源
    		Web12306 web =new Web12306();
    		System.out.println(Thread.currentThread().getName());
    		//多个代理
    		new Thread(web,"黄牛甲").start();
    		new Thread(web,"码农").start();
    		new Thread(web,"黄牛乙").start();;
    	}
    }
    
    重视基础,才能走的更远。
  • 相关阅读:
    Placing Rooks-CF 1342E
    Yet Another Counting Problem-CF 1342C
    [SDOI2016]齿轮
    Rinne Loves Xor
    Labyrinth CodeForces
    Nastya and Scoreboard
    Teacher Bo HDU
    Blood Cousins Return
    D Tree HDU
    设计模式学习笔记(八、行为型-策略模式)
  • 原文地址:https://www.cnblogs.com/xzlf/p/12681530.html
Copyright © 2011-2022 走看看