zoukankan      html  css  js  c++  java
  • java例程练习(关于线程同步的补充)

    /*
     * 从运行结果看,当m1()方法被锁定后,m2()方法仍然可以执行。
     * 而且b的值被改变。由此可以得出结论:
     * sychronized 只是防止其定义的代码段被同时调用。
     * 
     */
    
    
    public class Test implements Runnable{
    	int b = 100;
    	
    	public synchronized void m1() throws Exception {
    		b = 1000;
    		Thread.sleep(5000);
    		System.out.println("b = " + b);
    	}
    	
    	public void m2() {
    		System.out.println(b);
    	}
    	
    	public void run() {
    		try {
    			m1();
    		} catch(Exception e) {
    			e.printStackTrace();
    		}
    	}
    	
    	public static void main(String[] args) throws Exception {
    		Test t = new Test();
    		Thread th = new Thread(t);
    		th.start();
    		
    		Thread.sleep(1000);//确保线程启动
    		t.m2();
    	}
    	
    }
    /*
    运行结果:
    
    	1000
    	b = 1000
    
    */
    
    /*
     * 从运行结果看,当m1()方法被锁定后,m2()方法仍然可以执行。
     * 而且b的值被改变。由此可以得出结论:
     * sychronized 只是防止其定义的代码段被同时调用。
     * 将m2()锁定后,更改部分代码结果???
     * 
     */
    
    
    public class Test implements Runnable{
    	int b = 100;
    	
    	public synchronized void m1() throws Exception {
    		b = 1000;
    		Thread.sleep(5000);
    		System.out.println("b = " + b);
    	}
    	
    	public synchronized void m2() throws Exception {
    		Thread.sleep(2500);
    		b = 2000;
    	}
    	
    	public void run() {
    		try {
    			m1();
    		} catch(Exception e) {
    			e.printStackTrace();
    		}
    	}
    	
    	public static void main(String[] args) throws Exception {
    		Test t = new Test();
    		Thread th = new Thread(t);
    		th.start();
    		
    		Thread.sleep(1000);//确保线程启动
    		t.m2();
    		System.out.println(t.b);
    	}
    	
    }
    /*
    运行结果:
    
    	b = 1000
    	2000
    
    */
    


  • 相关阅读:
    腾讯// 反转字符串
    腾讯//Multiply Strings 字符串相乘
    腾讯//盛最多水的容器
    腾讯//删除排序数组中的重复项
    腾讯//删除排序数组中的重复项
    C语言中的预处理命令
    Python十大应用领域与就业方向
    Python的主要应用领域及应用场景
    Git命令_git status
    Git命令_git add快速添加文件到暂存区
  • 原文地址:https://www.cnblogs.com/wjchang/p/3671689.html
Copyright © 2011-2022 走看看