线程中的同步问题通常使用的是synchronized块,结合wait和notify方法,今天简单做了一个测试。发现当一个线程锁定了某个临界资源后另一个线程会自动等待,以往自己还认为需要自己写代码让其等待呢。。。


共享资源:

package sm.model;

import org.apache.log4j.Logger;

public class ThreadFuncs {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ThreadFuncs.class);

	private int shareNum;
	
	public ThreadFuncs(int initShareNum)
	{
		this.shareNum = initShareNum;
	}

	public void run1() {
		if (shareNum < 10) {
			synchronized (this) {
				for (; shareNum < 30; shareNum++) {
					logger.info("I go to print " + shareNum);
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					if (shareNum == 10) {
						try {
							this.wait();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

	public void run2() {
		/*logger.info("I am in run2 " + shareNum);

		while (shareNum == 0) {
			try {
				logger.info("I am in while " + shareNum);
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}*/

		synchronized (this) {
			for (; shareNum < 20; shareNum++) {
				logger.info("print " + shareNum);
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			this.notify();
		}

	}
}

线程1:

package sm.examples.threaddemo;

import sm.model.ThreadFuncs;

public class Thread3_1 extends Thread {

	private ThreadFuncs funcs;
	
	public Thread3_1(ThreadFuncs funcs)
	{
		this.funcs = funcs;
	}
	
	@Override
	public void run() {
		funcs.run1();
	}

}

线程2:

package sm.examples.threaddemo;

import sm.model.ThreadFuncs;

public class Thread3_2 extends Thread {

	private ThreadFuncs funcs;
	
	public Thread3_2(ThreadFuncs funcs)
	{
		this.funcs = funcs;
	}
	
	@Override
	public void run() {
		funcs.run2();
	}

}

测试类:

package sm.test;

import org.junit.Test;

import sm.examples.threaddemo.Thread3_1;
import sm.examples.threaddemo.Thread3_2;
import sm.model.ThreadFuncs;

public class TestThreadWaitNotifyDemo {
	@Test
	public void test()
	{
		ThreadFuncs funcs = new ThreadFuncs(0);
		
		Thread t1 = new Thread3_1(funcs);
		Thread t2 = new Thread3_2(funcs);
		
		t1.start();
		t2.start();
		
		try {
			Thread.sleep(100000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
			
}