02_线程基础(二)

示例002

package com.bjsxt.base.sync002;
/**
 * 关键字synchronized取得的锁都是对象锁,而不是把一段代码(方法)当作锁,
 * 因此代码中哪一个线程先执行synchronized关键字的方法,哪一个线程就持有该方法所属对象的锁(Lock),
 * 
 * 在静态方法上加synchronized关键字,表示锁定.class类,类一级别的锁(独占.class类)。
 * @author alienware
 *
 */
public class MultiThread {
    //Cannot make a static reference to the non-static field num
	//private int num = 0;
	
	/** static */
	public static synchronized void printNum(String tag){
		try {
			int num = 0;
			if(tag.equals("a")){
				num = 100;
				System.out.println("tag a, set num over!");
				Thread.sleep(1000);
			} else {
				num = 200;
				System.out.println("tag b, set num over!");
			}
			
			System.out.println("tag " + tag + ", num = " + num);
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	//注意观察run方法输出顺序
	public static void main(String[] args) {
		
		//俩个不一样的对象
		final MultiThread m1 = new MultiThread();
		final MultiThread m2 = new MultiThread();
		
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				m1.printNum("a");
			}
		});
		
		Thread t2 = new Thread(new Runnable() {
			@Override 
			public void run() {
				m2.printNum("b");
			}
		});		
		
		t1.start();
		t2.start();
		
	}
	
	
	
	
}

不带synchronized的输出

tag a, set num over!
tag b, set num over!
tag b, num = 200
tag a, num = 100

带synchronized的输出

tag a, set num over!
tag a, num = 100
tag b, set num over!
tag b, num = 200

示例003

package com.bjsxt.base.sync003;

/**
 * 对象锁的同步和异步问题
 * @author alienware
 *
 */
public class MyObject {

	public synchronized void method1(){
		try {
			System.out.println(Thread.currentThread().getName());
			Thread.sleep(4000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	/** synchronized */
	public  void method2(){
			System.out.println(Thread.currentThread().getName());
	}
	
	public static void main(String[] args) {
		
		final MyObject mo = new MyObject();
		
		/**
		 * 分析:
		 * t1线程先持有object对象的Lock锁,t2线程能够以异步的方式调用对象中的非synchronized修饰的方法,而无需等待
		 * t1线程先持有object对象的Lock锁,t2线程若是在这个时候调用对象中的同步(synchronized)方法则需等待,也就是同步
		 */
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				mo.method1();
			}
		},"t1");
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				mo.method2();
			}
		},"t2");
		
		t1.start();
		t2.start();
		
	}
	
}
相关文章
相关标签/搜索