同期スレッド2
1319 ワード
class DataObject {
int dataItem1;
int dataItem2;
DataObject() {
dataItem1 = 50;
dataItem2 = 50;
}
synchronized void itemSwap() {
int x = ( int )( -4.999999 + Math.random() * 10 );
dataItem1 -= x;
keepBusy( 10 );
dataItem2 += x;
}
synchronized void test() {
int sum = dataItem1 + dataItem2;
System.out.println( sum );
}
public void keepBusy( int howLong ) {
long curt = System.currentTimeMillis();
while( System.currentTimeMillis() < curt + howLong);
}
}
class RepeatedSwaps extends Thread {
DataObject dobj;
RepeatedSwaps( DataObject d ) {
dobj = d;
start();
}
public void run() {
int i = 0;
while( i++ < 200 ) {
dobj.itemSwap();
if( i % 40 == 0 ) {
dobj.test();
}
try {
sleep( i );
}catch( InterruptedException e) {}
}
}
}
public class SynchedSwaps {
public static void main(String[] args) {
DataObject d = new DataObject();
new RepeatedSwaps( d );
new RepeatedSwaps( d );
new RepeatedSwaps( d );
new RepeatedSwaps( d );
}
}