スレッド競合1

1386 ワード

class DataObject {
	int dataItem1;
	int dataItem2;
	DataObject() {
		dataItem1 = 50;
		dataItem2 =50;
	}
	void itemSwap() {
		int x = (int)( -4.999999+Math.random() * 10);
		dataItem1 -= x;
		keepBusy( 10 );
		dataItem2 += x;
	}
	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<20000 ) {
			dobj.itemSwap();
			if( i % 4000 == 0 ) {
				dobj.test();
			} 
			try {
				sleep( ( int )( Math.random() * 2 ) );
			}catch( InterruptedException e) {}
			i++;
		}
	}
}
public class UnsynchedSwaps {
	public static void main(String[] args) {
		DataObject d = new DataObject();
		new RepeatedSwaps( d );
		new RepeatedSwaps( d );
		new RepeatedSwaps( d );
		new RepeatedSwaps( d );
		new RepeatedSwaps( d );
		new RepeatedSwaps( d );
	}	
}