Java多线程:线程同步——实验4

原文地址: http://blog.csdn.net/huang_xw/article/details/7318554
/**
 * @Description: 两个线程(线程1与线程2)访问同一个类的静态同步方法syn()
 * 				 结果: 线程1访问对象sameObj1的静态同步方法syn()时, 线程2访问对象sameObj2中的静态同步方法syn()阻塞. 或者线程2访问时, 线程1阻塞.
 * 				 结论: 不同线程访问同一个类的静态同步方法时, 线程间是互斥的. 
 * @author snoopy
 * @blog http://blog.csdn.net/huang_xw
 */
package basic.b_syn;

import org.apache.log4j.Logger;

public class TestSynD {
	private static Logger logger = Logger.getLogger(TestSynD.class);

	// 线程1
	static class T1 implements Runnable {
		TestSynD s;

		public T1(TestSynD sameObj) {
			this.s = sameObj;
		}

		// 线程1访问静态同步方法
		public void run() {
			logger.debug("启动线程1...........");
			TestSynD.syn();
			logger.debug("退出线程1...........");
		}
	}

	// 线程2
	static class T2 implements Runnable {
		TestSynD s;

		public T2(TestSynD sameObj) {
			this.s = sameObj;
		}

		// 线程2访问静态同步方法
		public void run() {
			logger.debug("启动线程2...........");
			TestSynD.syn();
			logger.debug("退出线程2...........");
		}
	}

	// 对象的静态同步方法
	public static synchronized void syn() {
		String threadStr = Thread.currentThread().getName();
		logger.debug("▲▲▲▲▲▲" + threadStr + "开始访问静态同步方法");
		try {
			logger.debug(threadStr + "正在静态访问同步方法syn()!!!");
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		logger.debug("▲▲▲▲▲▲" + threadStr + "退出静态同步方法");
	}
	
	public static void main(String[] args) {
		// 这是多线程要访问的同一个对象
		TestSynD sameObj1 = new TestSynD();
		TestSynD sameObj2 = new TestSynD();

		// 线程1,线程2访问静态同步方法
		Thread t1 = new Thread(new T1(sameObj1));
		Thread t2 = new Thread(new T2(sameObj2));

		t1.start();
		t2.start();
	}
}

执行结果:

0    [Thread-0] DEBUG basic.b_syn.TestSynD - 启动线程1...........
0    [Thread-1] DEBUG basic.b_syn.TestSynD - 启动线程2...........
1    [Thread-0] DEBUG basic.b_syn.TestSynD - ▲▲▲▲▲▲Thread-0开始访问静态同步方法
1    [Thread-0] DEBUG basic.b_syn.TestSynD - Thread-0正在静态访问同步方法syn()!!!
3001 [Thread-0] DEBUG basic.b_syn.TestSynD - ▲▲▲▲▲▲Thread-0退出静态同步方法
3001 [Thread-1] DEBUG basic.b_syn.TestSynD - ▲▲▲▲▲▲Thread-1开始访问静态同步方法
3001 [Thread-1] DEBUG basic.b_syn.TestSynD - Thread-1正在静态访问同步方法syn()!!!
3001 [Thread-0] DEBUG basic.b_syn.TestSynD - 退出线程1...........
6002 [Thread-1] DEBUG basic.b_syn.TestSynD - ▲▲▲▲▲▲Thread-1退出静态同步方法
6002 [Thread-1] DEBUG basic.b_syn.TestSynD - 退出线程2...........

你可能感兴趣的:(java,thread,多线程,String,Blog,Class)