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

      

  • 相关阅读:
    diary and html 文本颜色编辑,行距和其它编辑总汇
    bash coding to changeNames
    virtualbox ubuntu 网络连接 以及 连接 secureCRT
    linux 学习6 软件包安装
    linux 学习8 权限管理
    vim 使用2 转载 为了打开方便
    ubuntu
    linux 学习15 16 启动管理,备份和恢复
    linux 学习 14 日志管理
    linux 学习 13 系统管理
  • 原文地址:https://www.cnblogs.com/aituming/p/4778629.html
Copyright © 2011-2022 走看看