zoukankan      html  css  js  c++  java
  • 线程同步两种方式

    package test.access.foreign;
    
    public class Foreign {
    	
    	public static void main(String args[]){
    		MyThread mt=new MyThread();
    		for(int i=0;i<20;i++)//模拟20个售票终端
    		new Thread(mt).start();
    	}
    	/**
    	 * 打印结果:
    	 */
    }
    class MyThread implements Runnable{
    	int tacket=5;
    	@Override
    	public void run() {
    		try {
    			
    				sale();
    			
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}		
    	}
    	private synchronized void sale() throws InterruptedException{
    		long time=(long) (Math.random()*5000);
    		System.out.println("线程"+Thread.currentThread().getName()+"休眠"+time+"毫秒");
    		Thread.sleep(time);//模拟网络延时
    		if(tacket>=1){
    			System.out.println("售票:"+tacket--);
    		}else{
    			System.out.println("没票啦");
    		}
    	}
    }

    方式二:
    package test.access.foreign;
    
    public class Foreign {
    	
    	public static void main(String args[]){
    		MyThread mt=new MyThread();
    		for(int i=0;i<20;i++)//模拟20个售票终端
    		new Thread(mt).start();
    	}
    	/**
    	 * 打印结果:
    	 */
    }
    class MyThread implements Runnable{
    	int tacket=5;
    	@Override
    	public void run() {
    		try {
    			synchronized(this){
    				long time=(long) (Math.random()*5000);
    				System.out.println("线程"+Thread.currentThread().getName()+"休眠"+time+"毫秒");
    				Thread.sleep(time);//模拟网络延时
    				if(tacket>=1){
    					System.out.println("售票:"+tacket--);
    				}else{
    					System.out.println("没票啦");
    				}
    			}
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}		
    	}
    }

  • 相关阅读:
    python编写弹球游戏的实现代码
    Linux kernal
    ccc
    Ubuntu14.04 支持 exFat 格式操作
    Ubuntu 14.04 tar 打包系统安装到新机器
    Ubuntu14.04 dd命令克隆系统镜像安装到另一台机器上
    gzip 的使用
    gzip: stdin: unexpected end of file tar: Unexpected EOF in archive
    c++ 实现等待5s
    Ubuntu14.04 系统复制迁移到新的机器上
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/6893112.html
Copyright © 2011-2022 走看看