Thursday, August 17, 2006

Run Threads in Java


package test2;

/**
* The output is something like 0 3 4 1 2 5 6 7 8 9
* Note all threads are associated with one object.
*/
public class ThreadTest implements Runnable {
int counter;

public static void main(String args[]) {
Runnable run = new ThreadTest();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(run);
thread.setDaemon(true); // so program can exit
thread.start();
}
}

public void run() {
System.out.println(counter++);
for (int j = 0; j < 100000000; j++) {
String x = "" + Math.sqrt(1.2111);
}
System.out.println( " counter=" + counter++);
}
}

0 Comments:

Post a Comment

<< Home