Montag, 8. Dezember 2008

java : 3 steps to threads

EE3206/EE5805 Java programming and Applications

notes on Liang(2009), p.958-961:

Three steps to start a thread

1. create a class that implements the Runnable interface and implements the run() method.

2. new() a thread object by passing the Runnable object to the Thread class

3. start threads by invoking the start() method

////////////////////////////////////

public class TaskThreadDemo {
public static void main(String[] args)
{
// create tasks
Runnable printA = new PrintChar('a', 100);
Runnable printB = new PrintChar('b', 100);
Runnable print100 = new PrintNum(100);

// 2. create thread objects by passing
// the Runnable object to the Thread class
Thread thread1 = new Thread(printA);
Thread thread2 = new Thread(printB);
Thread thread3 = new Thread(print100);

// 3. start threads
thread1.start();
thread2.start();
thread3.start();

}

//////////////////////////////////////////////////

public class PrintChar implements Runnable
{
// 1. implements th Runnable interface and implements the run() method

private char charToPrint; //the characte to print
private int times; // the number of times to print

public PrintChar(char c, int t)
{
charToPrint = c;
times = t;

}
public void run()
{
for (int i=0; i< times; i++)
System.out.print(charToPrint);

}
}

///////////////////////////////////////

public class PrintNum implements Runnable
{
private int lastNum;

/** a task to print 1,2,3, ...i */
public PrintNum(int n)
{
lastNum =n;

}

public void run()
{
for(int i=1; i<= lastNum; i++)
System.out.print(" " + i);
}
}





Keine Kommentare: