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();		
    	}
    }
    

      

  • 相关阅读:
    HDU 5583 Kingdom of Black and White 水题
    HDU 5578 Friendship of Frog 水题
    Codeforces Round #190 (Div. 2) E. Ciel the Commander 点分治
    hdu 5594 ZYB's Prime 最大流
    hdu 5593 ZYB's Tree 树形dp
    hdu 5592 ZYB's Game 树状数组
    hdu 5591 ZYB's Game 博弈论
    HDU 5590 ZYB's Biology 水题
    cdoj 1256 昊昊爱运动 预处理/前缀和
    cdoj 1255 斓少摘苹果 贪心
  • 原文地址:https://www.cnblogs.com/aituming/p/4778629.html
Copyright © 2011-2022 走看看