⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 synchblock.java

📁 Java网络编程与分布式计算, 主要分析java网络各方面的编程, 提供许多实用安全
💻 JAVA
字号:
// 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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -