Java Reference
In-Depth Information
while (true)
System.out.println(name+":
"+count++);
}
};
Thread thdA = new Thread(r);
Thread thdB = new Thread(r);
thdA.start();
thdB.start();
}
}
tiates an anonymous class that implements
Runnable
. It then creates two
Thread
objects,initializingeachobjecttotherunnable,andcalls
Thread
's
start()
method
to create and start both threads. After completing these tasks, the main thread exits
main()
and dies.
Each of the two started threads executes the runnable's
run()
method. It calls
Thread
's
currentThread()
method to obtain its associated
Thread
instance,
usesthisinstancetocall
Thread
's
getName()
methodtoreturnitsname,initializes
count
to0,andentersaninfiniteloopwhereitoutputs
name
and
count
,andincre-
ments
count
on each iteration.
Tip
To stop an application that does not end, press the Ctrl and C keys simultan-
eously (at least on Windows platforms).
IobserveboththreadsalternatingintheirexecutionwhenIrunthisapplicationonthe
Windows XP platform. Partial output from one run appears here:
Thread-0: 0
Thread-0: 1
Thread-0: 2
Thread-0: 3
Thread-0: 4
Thread-0: 5
Thread-0: 6
Thread-0: 7
Thread-1: 0