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

      

  • 相关阅读:
    MySQL事务隔离级别(InnoDB)
    Kettle连接SQL Server数据库
    jstack分析Java进程信息
    Java对Map集合进行排序
    Java堆分析 jmap+jhat
    Oracle列转行 参数动态传入iBatis使用示例
    Hive UDF函数测试
    test
    《串并行数据结构与算法(SML语言)实验》题解
    educoder SML程序设计题线下编译环境搭建
  • 原文地址:https://www.cnblogs.com/aituming/p/4778629.html
Copyright © 2011-2022 走看看