java 线程同步

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程同步  synchronize  
 */
public class TraditionalThreadSynchronized {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new TraditionalThreadSynchronized().init();
	}
	
	private void init(){
		final Outputer out=new Outputer();
		new Thread(
		new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (true) {
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					out.output("English");
				}
			}
		}
		).start();
		
		new Thread(
			new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					while (true) {
						try {
							Thread.sleep(10);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						out.output("Chinese");
					}
					
				}
			}
		).start();
		
	}
	
	//使用各种 同步锁对象   this,.class ,Object ,Lock 
	static class Outputer{
		String sync="";
		public void output(String name){
			int len=name.length();
			synchronized(this){  //只有是同一对象的时候才能用this,否则  只能用.class,或者 建立一个  static Object sycn
				for (int i = 0; i < len; i++) {
					System.out.print(name.charAt(i));
				}
				System.out.println();
			}
		} 
		
		public synchronized void output2(String name){  //使用的是 this 
			int len=name.length();
				for (int i = 0; i < len; i++) {
					System.out.print(name.charAt(i));
				}
				System.out.println();
		} 
		
		
		public static synchronized void output3(String name){  //使用的是 .class 
			int len=name.length();
				for (int i = 0; i < len; i++) {
					System.out.print(name.charAt(i));
				}
				System.out.println();
		}
		
		Lock lock=new ReentrantLock();
		public void output4(String name){
			int len=name.length();
			lock.lock();   //使用 jdk 1.5 提供的锁
			try {
				for (int i = 0; i < len; i++) {
					System.out.print(name.charAt(i));
				}
				System.out.println();
			} catch (Exception e) {
				// TODO: handle exception
			}finally{
				lock.unlock();
			}
				
		} 
		
		
		
	}

}

猜你喜欢

转载自takeme.iteye.com/blog/2314808