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

📄 communicationdemo.java

📁 精通Java核心技术的随书源代码
💻 JAVA
字号:
public class CommunicationDemo implements Runnable
	{
		int time=0;
		
		// 创建并启动两个线程
		public CommunicationDemo() 
		{
			Thread thread1 = new Thread(this,"read");
			Thread thread2 = new Thread(this,"write");
			thread2.start();
			thread1.start();
		}
		
		// override run方法
		public void run()
		{
			Thread t = Thread.currentThread();
			
			try {
				// 先让write线程处于等待状态
				if (!t.getName().equals("read")) 
				{
					synchronized(this) 
					{
						wait();
					}
				}
				
				while(true)
				{
					System.out.println( t.getName()+ " thread is running." );
	
					time ++;
					
					// 一个线程连续运行两次即进入等待状态,并唤醒其他线程
					if(time % 2 == 0) 
					{
						synchronized(this) 
						{
							System.out.println( "*****************************" );
							notify();
							if ( time == 8 ) break;
							wait();
						}
					}
				}
			}
			catch(Exception e) {
				e.printStackTrace();
			}
		}
		
		public static void main(String[] args) 
		{ 
			CommunicationDemo comDemo = new CommunicationDemo();
		}
	}

⌨️ 快捷键说明

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