📄 sharedcell1.java
字号:
// Show multiple threads modifying shared object.
public class SharedCell
{
public static void main( String args[] )
{
HoldIntegerSynchronized h = new HoldIntegerSynchronized();
ProduceInteger p = new ProduceInteger( h );
ConsumeInteger c = new ConsumeInteger( h );
p.start();
c.start();
}
}
// Definition of threaded class ProduceInteger
public class ProduceInteger extends Thread
{
private HoldIntegerSynchronized pHold;
public ProduceInteger( HoldIntegerSynchronized h )
{
super( "ProduceInteger" );
pHold = h;
}
public void run()
{
for ( int count = 1; count <= 10; count++ )
{
// sleep for a random interval
try
{
Thread.sleep( (int) ( Math.random() * 3000 ) );
}
catch( InterruptedException e )
{
System.err.println( e.toString() );
}
pHold.setSharedInt( count );
}
System.err.println( getName() + " finished producing values" + "\nTerminating " + getName() );
}
}
// Definition of threaded class ConsumeInteger
public class ConsumeInteger extends Thread
{
private HoldIntegerSynchronized cHold;
public ConsumeInteger( HoldIntegerSynchronized h )
{
super( "ConsumeInteger" );
cHold = h;
}
public void run()
{
int val, sum = 0;
do
{
// sleep for a random interval
try
{
Thread.sleep( (int) ( Math.random() * 3000 ) );
}
catch( InterruptedException e )
{
System.err.println( e.toString() );
}
val = cHold.getSharedInt();
sum += val;
}
while ( val != 10 );
System.err.println( getName() + " retrieved values totaling: " + sum + "\nTerminating " + getName() );
}
}
// Definition of class HoldIntegerSynchronized that
// uses thread synchronization to ensure that both
// threads access sharedInt at the proper times.
public class HoldIntegerSynchronized
{
private int sharedInt = -1;
private boolean writeable = true; // condition variable
public synchronized void setSharedInt( int val )
{
while ( !writeable )
{
// not the producer's turn
try
{
wait();
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
}
System.err.println( Thread.currentThread().getName() + " setting sharedInt to " + val );
sharedInt = val;
writeable = false;
notify(); // tell a waiting thread to become ready
}
public synchronized int getSharedInt()
{
while ( writeable )
{
// not the consumer's turn
try
{
wait();
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
}
writeable = true;
notify(); // tell a waiting thread to become ready
System.err.println( Thread.currentThread().getName() + " retrieving sharedInt value " + sharedInt );
return sharedInt;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -