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

原文地址: http://blog.csdn.net/huang_xw/article/details/7318554
/**
 * @Description: 线程1访问线程安全对象StringBuffer的实例, 线程2要访问时该对象则会出现阻塞现象.
 * @author snoopy
 * @blog http://blog.csdn.net/huang_xw
 */
package basic.b_syn;

import org.apache.log4j.Logger;

public class TestSynE {
	private static Logger logger = Logger.getLogger(TestSynE.class);
	StringBuffer sb = new StringBuffer("初始字符串+");

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

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

		// 线程1访问方法syn1()
		public void run() {
			logger.debug("启动线程1...........");
			s.syn1();
			logger.debug("退出线程1...........");
		}
	}

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

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

		// 线程2访问方法syn2()
		public void run() {
			logger.debug("启动线程2...........");
			s.syn2();
			logger.debug("退出线程2...........");
		}
	}

	public void syn1() {
		String threadStr = Thread.currentThread().getName();
		logger.debug("▲▲▲▲▲▲" + threadStr + "开始访问方法syn1()");
		try {
			synchronized (sb) {
				logger.debug(threadStr + "正在访问对象sb");
				sb.append("线程1加入的字符串+");
				// 用休眠模拟一个耗时过程
				Thread.sleep(5000);
				logger.debug(threadStr + "休眠结束");
				logger.debug("此时字符串为: " + sb.toString());
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		logger.debug("▲▲▲▲▲▲" + threadStr + "退出方法syn1()");
	}

	public void syn2() {
		String threadStr = Thread.currentThread().getName();
		logger.debug("●●●●●●" + threadStr + "开始访问方法syn2()");
		sb.append("线程2加入的字符串+");
		logger.debug("此时字符串为: " + sb.toString());
		logger.debug("●●●●●●" + threadStr + "退出方法syn2()");
	}

	public static void main(String[] args) {
		// 这是多线程要访问的同一个对象
		TestSynE sameObj = new TestSynE();

		// 线程1访问同步方法syn1(), 线程2同样也访问同步方法syn2().
		Thread t1 = new Thread(new T1(sameObj), "线程1");
		Thread t2 = new Thread(new T2(sameObj), "线程2");

		t1.start();
		// sleep是为保证线程1先开始运行, 首先访问StringBuffer的实例.
		try {
			Thread.sleep(50);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		t2.start();
	}
}
执行结果:
0    [线程1] DEBUG basic.b_syn.TestSynE - 启动线程1...........
0    [线程1] DEBUG basic.b_syn.TestSynE - ▲▲▲▲▲▲线程1开始访问方法syn1()
0    [线程1] DEBUG basic.b_syn.TestSynE - 线程1正在访问对象sb
49   [线程2] DEBUG basic.b_syn.TestSynE - 启动线程2...........
49   [线程2] DEBUG basic.b_syn.TestSynE - ●●●●●●线程2开始访问方法syn2()
5000 [线程1] DEBUG basic.b_syn.TestSynE - 线程1休眠结束
5001 [线程1] DEBUG basic.b_syn.TestSynE - 此时字符串为: 初始字符串+线程1加入的字符串+
5001 [线程1] DEBUG basic.b_syn.TestSynE - ▲▲▲▲▲▲线程1退出方法syn1()
5001 [线程2] DEBUG basic.b_syn.TestSynE - 此时字符串为: 初始字符串+线程1加入的字符串+线程2加入的字符串+
5001 [线程1] DEBUG basic.b_syn.TestSynE - 退出线程1...........
5001 [线程2] DEBUG basic.b_syn.TestSynE - ●●●●●●线程2退出方法syn2()
5001 [线程2] DEBUG basic.b_syn.TestSynE - 退出线程2...........



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