zoukankan      html  css  js  c++  java
  • Java中同步

    解决资源共享的同步操作,有两种方法:一是同步代码块,二是同步方法。

    在需要同步的代码块加上synchronized关键字,

    同步代码块时必须指定一个需要同步的对象,但一般都是将当前对象(this)设置成同步对象。

    class Thread8 implements Runnable{
    	private int ticket = 5;
    	public void run(){
    		for(int i=0; i<100; i++){
    			synchronized (this) {
    				if(ticket>0){
    					try {
    						Thread.sleep(300);
    					} catch (Exception e) {
    						// TODO: handle exception
    						e.printStackTrace();
    					}
    					System.out.println("买票: ticket = "+ticket--);
    				}
    			}
    			
    		}
    	}
    }
    
    public class SyncDemo {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Thread8 tt = new Thread8();
    		Thread t1 = new Thread(tt);
    		Thread t2 = new Thread(tt);
    		Thread t3 = new Thread(tt);
    		
    		t1.start();
    		t2.start();
    		t3.start();
    	}
    
    }
    

      同步方法使用synchronized关键字将一个方法声明成同步方法。格式如下:

    class Thread9 implements Runnable{
    	private int ticket = 5;
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		for(int i = 0; i<100; i++){
    			this.sale();
    		}
    	}
    	
    	public synchronized void sale(){
    		if (ticket>0) {
    			try {
    				Thread.sleep(300);
    			} catch (Exception e) {
    				// TODO: handle exception
    				e.printStackTrace();
    			}
    			System.out.println("买票: ticket = "+ ticket--);
    		}
    	}
    }
    
    
    public class SyncDemo02 {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Thread9 tt = new Thread9();
    		Thread t1 = new Thread(tt);
    		Thread t2 = new Thread(tt);
    		Thread t3 = new Thread(tt);
    		
    		t1.start();
    		t2.start();
    		t3.start();		
    	}
    }
    

      

  • 相关阅读:
    我要翻译《Think Python》- 004 第二章 变量, 表达式和语句
    我要翻译《Think Python》-003 第一章 编程之道
    我要翻译《Think Python》-002 贡献列表 & 目录部分
    我要翻译《Think Python》
    ORA-12514 解决方法
    好玩的东西
    sublime HtmlPrettify
    [转]bing壁纸天天换 初识shell魅力
    nginx+lua+redis 处理APK包替换
    算法整理
  • 原文地址:https://www.cnblogs.com/aituming/p/4778629.html
Copyright © 2011-2022 走看看