📄 j_synchronization.java.bak
字号:
// ////////////////////////////////////////////////////////
//
// J_Synchronization.java
//
// Created by Jun-Hai Yong, on XX xx, xxxx (Date)
// ////////////////////////////////////////////////////////
// Readme:
// Demonstrating synchronization of threads.
// ////////////////////////////////////////////////////////
// Using this example, please explicitly refer to the book:
// Jun-Hai Yong. Programming in Java.
// Beijing: Tsinghua University Press, 2004.
// 使用本例子,请注明引用:
// 雍俊海. Java 程序设计. 北京: 清华大学出版社, 2004.
// Please note that the author and publisher make no
// warranty of any kind on the examples provided.
// ////////////////////////////////////////////////////////
class J_Experiment
{
private int m_temperature, m_pressure;
public void mb_update(int t, int p)
{
m_temperature = t;
m_pressure = p;
System.out.println("Update: (" + m_temperature + "(t), " + m_pressure + "(p))");
} // End of method: mb_update
public void mb_analyze( )
{
int t= m_temperature;
int p= m_pressure;
if (t!=m_temperature)
{
System.out.print("It is very dangerous now: ");
System.out.println("t(" + t + ") != (" + m_temperature + ")");
System.exit(0);
}
if (p!= m_pressure)
{
System.out.print("It is very dangerous now: ");
System.out.println("p(" + p + ") != (" + m_pressure + ")");
System.exit(0);
}
System.out.println("Analyze: (" + m_temperature + "(t), " + m_pressure + "(p))");
} // End of method: mb_analyze
} // End of class: J_Experiment
class J_Assistant extends Thread
{
J_Experiment m_data;
public J_Assistant(J_Experiment d)
{
m_data= d;
} // End of constructor
public void run( )
{
int i, j;
for(; true; )
{
i= (int)(Math.random( ) * 1000);
j= (int)(Math.random( ) * 1000);
synchronized(m_data)
{
m_data.mb_update(i, j);
}
}
} // End of method: run
} // End of class: J_Assistant
class J_Analyst extends Thread
{
J_Experiment m_data;
public J_Analyst(J_Experiment d)
{
m_data= d;
} // End of constructor
public void run( )
{
int i;
for(; true; )
{
synchronized(m_data)
{
m_data.mb_analyze( );
}
}
} // End of method: run
} // End of class: J_Analyst
public class J_Synchronization
{
public static void main( String args[] )
{
J_Experiment data= new J_Experiment( );
J_Assistant threadA = new J_Assistant(data);
J_Analyst threadB = new J_Analyst(data);
threadA.start( );
threadB.start( );
} // End of method: main
} // End of class: J_Synchronization
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -