synchblock.java

来自「Java网络编程与分布式计算, 主要分析java网络各方面的编程, 提供许多实用」· Java 代码 · 共 53 行

JAVA
53
字号
// Chapter 7, Listing 7
public class SynchBlock implements Runnable
{
	StringBuffer buffer;
	int counter;

	public SynchBlock()
	{
		buffer = new StringBuffer();
		counter= 1;
	}

	public void run()
	{
		
		synchronized (buffer)
		{
			System.out.print ("Starting synchronized block ");
			int tempVariable = counter++;

			// Create message to add to buffer, including linefeed
			String message = "Count value is : " + tempVariable +
				System.getProperty("line.separator");


			try
			{
				Thread.sleep(100);
			}
			catch (InterruptedException ie) {}

			buffer.append (message);
			System.out.println ("... ending synchronized block");
		}
	}

	public static void main(String args[]) throws Exception
	{
		// Create a new runnable instance
		SynchBlock block = new SynchBlock();

		Thread t1 = new Thread (block);
		Thread t2 = new Thread (block);
		Thread t3 = new Thread (block);
		Thread t4 = new Thread (block);
		t1.start(); t2.start(); t3.start(); t4.start();

		// Wait for all three threads to finish
		t1.join(); t2.join(); t3.join(); t4.join();

		System.out.println (block.buffer);
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?