Friday, August 6, 2010

Multithreading

Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065)
Chapter 9, Exercise 9-1
 
In this exercise we will create a simple counting thread. It will count to 100, pausing one second between each number. Also, in keeping with the counting theme, it will output a string every ten numbers.

1. Create a class and extend the Thread class. As an option, you can implement the Runnable interface.

class TheCount extends Thread{

2. Override the run() method of Thread. This is where the code will go that will output the numbers.

public void run(){ 

3. Create a for loop that will loop 100 times. Use the modulo operation to check whether there are any remainder numbers when divided by 10.

for (int i=1; i<100; i++){

....

if (i % 10 == 0)

4. Use the static method Thread.sleep() to pause. (Remember, the one-arg version of sleep() specifies the amount of time of sleep in milliseconds.)

try{Thread.sleep(1000);}

Possible solution:

No comments:

Post a Comment