zoukankan      html  css  js  c++  java
  • Java 线程同步

    同步代码块:在代码块前加上“synchronized”关键字,则称此代码块为同步代码块
    格式:
        synchronized(同步对象){
            需要同步的代码块
        }
    同步方法:方法也可以同步
    格式:
        synchronized void 方法名(){}


    同步代码块:

    class MyThreadDemo implements Runnable {
    	private int ticket=5;
    	public void run() {
    		for (int i = 0; i < 10; i++) {
    			if (ticket>0) {
    				try {
    					Thread.sleep(500);
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    				System.out.println("车票:"+ticket--);
    			}
    		}
    	}
    }
    public class ThreadDemo04 {
    
    	public static void main(String[] args) {
    		MyThreadDemo m=new MyThreadDemo();
    		Thread t1=new Thread(m);
    		Thread t2=new Thread(m);
    		Thread t3=new Thread(m);
    		
    		t1.start();
    		t2.start();
    		t3.start();
    	}
    
    }
    

     输出:

    车票:5
    车票:3
    车票:4
    车票:2
    车票:0
    车票:1
    

     车票应该从大到小递减的,说明程序执行过程中run方法里的代码块没有同步。

    加入同步:

    class MyThreadDemo implements Runnable {
    	private int ticket=5;
    	public void run() {
    		for (int i = 0; i < 10; i++) {
    			synchronized (this) {
    				if (ticket>0) {
    					try {
    						Thread.sleep(500);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					System.out.println("车票:"+ticket--);
    				}
    			}
    			
    		}
    	}
    }
    public class ThreadDemo04 {
    
    	public static void main(String[] args) {
    		MyThreadDemo m=new MyThreadDemo();
    		Thread t1=new Thread(m);
    		Thread t2=new Thread(m);
    		Thread t3=new Thread(m);
    		
    		t1.start();
    		t2.start();
    		t3.start();
    	}
    
    }
    

     输出:

    车票:5
    车票:4
    车票:3
    车票:2
    车票:1
    

    同步方法:

    class MyThreadDemo implements Runnable {
    	private int ticket=5;
    	public void run() {
    			tell();
    	}
    	public synchronized void tell() {
    		for (int i = 0; i < 10; i++) {
    			if (ticket>0) {
    				try {
    					Thread.sleep(500);
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    				System.out.println("车票:"+ticket--);
    		}
    		}
    	}
    }
    public class ThreadDemo04 {
    
    	public static void main(String[] args) {
    		MyThreadDemo m=new MyThreadDemo();
    		Thread t1=new Thread(m);
    		Thread t2=new Thread(m);
    		Thread t3=new Thread(m);
    		
    		t1.start();
    		t2.start();
    		t3.start();
    	}
    
    }
    

     输出同上。

  • 相关阅读:
    数组里的数据绑定到dataset中
    有关字符串匹配的方法
    sql语句全集
    Dialog 的6中提示方式
    android开源项目和框架
    MyEclipse DB Browser使用图文全攻略
    省市县联动(转)
    LRU算法
    Java 性能优化小细节
    HashMap
  • 原文地址:https://www.cnblogs.com/zhhy236400/p/10490919.html
Copyright © 2011-2022 走看看