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

     输出同上。

  • 相关阅读:
    CSS的应用
    关于新手html的认识 以及对table的基本用法
    javascript的使用方法
    CSS的使用方式和选择器的用法
    html基础知识点
    前端课堂第四课
    前端课堂第三课
    前端实训第二课
    前端实训随笔
    JS02
  • 原文地址:https://www.cnblogs.com/zhhy236400/p/10490919.html
Copyright © 2020-2023  润新知