FileDocCategorySizeDatePackage
SyncNeeded.javaAPI DocExample3205Sun Feb 08 21:34:08 GMT 2004None

SyncNeeded

public class SyncNeeded extends Object
Show a method that may fail due to lack of synchronization

Fields Summary
public static final int
MAX
protected static int[]
data
protected static int
ix
Constructors Summary
Methods Summary
public static voidmain(java.lang.String[] args)


	        
		class R implements Runnable {
			public void run() {
				// System.out.println(
				//	"Running " + Thread.currentThread().getName());

				// This statement may do bad things!
				data[ix] = ix++;
			}
		}
		data = new int[MAX];
		System.out.println("Starting " + MAX + " threads...");
		for (int i=0; i<MAX; i++) {
			new Thread(new R()).start();
		}
		System.out.println("Sleeping to let threads finish");
		Thread.sleep(4000);
		for (int i=0; i<MAX; i++) {
			if (i != data[i])
				System.out.println("Discrepancy at " + i + ": " + data[i]);
		}
		System.out.println("Done.");