好记性不如铅笔头

java, think_in_java, 编程

《Java编程思想》读书笔记:synchronized

最近在整理 Java 的多线程相关的技术,这里备份下关于【 synchronized 】代码。

github:

【 https://github.com/cstriker1407/think_in_java 】

SyncTest.java类:

public class SyncTest
{
	private static SyncTest instance = new SyncTest();
	
	public static void test()
	{
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				for (int i = 0; i < 5; i++)
				{
					instance.funA();
					
					try {
						Thread.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				for (int i = 0; i < 5; i++)
				{
					instance.funB();
					
					try {
						Thread.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();	
	}
	
	public synchronized void funA()
	{
		System.out.println("A start");
		
		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		System.out.println("A end");
	}
	
	public void funB()
	{
		synchronized (this)
		{
			System.out.println("B start");
			
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			System.out.println("B end");
		}
	}
}

部分日志打印:

A start
A end
B start
B end
A start
A end
B start
B end
A start
A end
B star

备注:

Leave a Reply

5 × 2 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据