Java----synchronized的小测试

方式一:方法内部修饰 

public class ThreadTest {

	public static List<Integer> forLey = new ArrayList<Integer>();

	public void doFun() {

		try {
			Thread.currentThread().sleep(600);
		} catch (Exception e) {
			e.printStackTrace();
		}

		synchronized (ThreadTest.class) {
			if (forLey.size() >= 1000)
				return;
			forLey.add(10);
			System.out.println(forLey.size());//打印1到1000
		}

	}

	public static void main(String[] args) {
		ThreadTest threadTest = new ThreadTest();
		for (int i = 0; i < 2000; i++) {
			Thread thread = new Thread(new MyRunnable(threadTest));
			thread.start();
		}
	}

}

class MyRunnable implements Runnable {
	private ThreadTest threadTest;

	public MyRunnable(ThreadTest threadTest) {
		this.threadTest = threadTest;
	}

	@Override
	public void run() {
		threadTest.doFun();
	}
}

 

 方式二:修饰方法

public class ThreadTest {

	public static List<Integer> forLey = new ArrayList<Integer>();

	// 修复实例方法,操作的ThreadTest的实例应为单实例(同一实例对象),可以注释CODE-1,打开CODE-2进行测试,程序会报错,或者打印不全
	// 或者将doFun方法加上 static静态修饰
	public synchronized void doFun() {	
		try {
			Thread.currentThread().sleep(600);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		if (forLey.size() >= 1000)
			return;
		forLey.add(10);
		System.out.println(forLey.size());// 打印1到1000
	}

	public static void main(String[] args) {
		ThreadTest threadTest = new ThreadTest(); // CODE-1
		for (int i = 0; i < 2000; i++) {
			// ThreadTest threadTest = new ThreadTest(); //CODE-2
			Thread thread = new Thread(new MyRunnable(threadTest));
			thread.start();
		}
	}

}



 

 

  • 1

    Java SE1.6中的Synchronized http://ifeve.com/java-synchronized/

  • 2

    java synchronized http://liyanblog.cn/articles/2012/11/02/1351841479203.html

     

     

     

     

     

     

     

     

     

     

     

     

     

     


     

  • 你可能感兴趣的:(Java----synchronized的小测试)