• 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
    
    */
    


  • 相关阅读:
    Ajax调用处理页面错误信息500的解决思路
    PHP数据库的增删改
    PHP登录及处理
    PHP数据访问
    PHP数组(正则表达式、数组、预定义数组)
    php函数
    45
    数据库_CRUD操作之读取数据之高级读取
    数据库_CRUD操作之读取数据
    数据库_CRUD操作之修改数据
  • 原文地址:https://www.cnblogs.com/wjchang/p/3671689.html
Copyright © 2020-2023  润新知