communicationdemo.java
来自「精通Java核心技术源代码」· Java 代码 · 共 58 行
JAVA
58 行
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 + =
减小字号Ctrl + -
显示快捷键?