线程间的互斥(synchronized )

  线程互斥是指某一资源同时只允许一个访问者对其进行访问,具有唯一性和排它性。但互斥无法限制访问者对资源的访问顺序,即访问是无序的。

 

/**
 * 线程间的互斥
 * @author MrRock
 *
 */
public class TraditionalThreadSynchronized  {
	
	public static void main(String[] args) {
		new TraditionalThreadSynchronized().init();
	}
	void init(){
		final Outputer out  = new Outputer();
		//线程1
		new Thread(new Runnable(){
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					out.output1("Tmethod--->AAAAAA");
				}
			}
			 
		}).start();
		//线程2
		new Thread(new Runnable(){
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					out.output3("Tmethod--->BBBBBB");
				}
			}
			
		}).start();
	} //end main
	
	static class Outputer{  //内部类
		/**
		 * 方法内部加上线程锁,线程的锁只能锁同一个对象,如果有static方法那么线程锁必须为Class,不能为this
		 */
		public void output1(String name){
			int len =name.length();
			synchronized (Outputer.class){ //synchronized参数可以为this,但是和static方法不能实现互斥,实现互斥只能为同一个对象
				for(int i=0;i<len;i++){
					System.out.print(name.charAt(i));
				}
				System.out.println();
			}
		}
		/**
		 * output2 和 output3不能实现同步,output2用的是对象锁的是this而output3是static方法要锁的话只能用class,如:output1
		 * @param name
		 */
		public synchronized void output2(String name){ //直接把锁加在方法上,默认把synchronized加载方法上那么他的互斥对象为this
			int len =name.length();
				for(int i=0;i<len;i++){
					System.out.print(name.charAt(i));
				}
				System.out.println();
		}
		//static方法的线程锁
		public static synchronized void output3(String name){
			int len =name.length();
			for(int i=0;i<len;i++){
				System.out.print(name.charAt(i));
			}
			System.out.println();
		}
	}
}

  

posted @ 2012-05-16 22:07  MrRock  阅读(882)  评论(0编辑  收藏  举报