Saturday, September 11, 2010

Code to Understand Objective 4.2

Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065)

4.2 Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.


/*
Let’s modify our Fred, Lucy, Ricky code by using sleep() to try to force the threads to alternate rather than letting one thread dominate for any period of time.
*/













Setting a Thread’s Priority

Courtesy of coderanch.com


/*
You can set a thread’s priority directly by calling the setPriority() method on a Thread instance as follows
*/











The yield() Method




















With Thread.yield(), you get the following output:
Pong bounced
Pong bounced
Ping bounced
Ping bounced
Ping = 3941 Pong = 3940

When you comment out Thread.yield, you get the following output:
Ping bounced
Ping bounced
Pong bounced
Pong bounced
Ping bounced
Ping = 3 Pong = 2

yield() gives turn to other threads. Sometimes one thread can take up all the CPU cycles.

The join() Method

/*If you remove t2.join(), then t2 and t1's execution are interleaved. With t2.join() in the picture, t2 finishes execution before t1 begins*/

No comments:

Post a Comment