“Computer Programming 2”
09 Hands-on Activity 2
Answers:
Extending the Thread class:
public class ThreadDemo extends Thread {
public static void main (String [] args) {
ThreadDemo thread = new ThreadDemo();
thread.start();
System.out.println("Outside of a thread");
}
public void run () {
System.out.println("Running in a thread");
}
}
Output:
The following sample program shows the use of setName (), getName (), and setPriority ().
public class ThreadDemo extends Thread {
public static void main (String [] args) {
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();
t1.setName("One");
t2.setName("Two");
t3.setName("Three");
t1.setPriority(4);
t2.setPriority(Thread.MAX_PRIORITY);
t3.setPriority(8);
t1.start();
t2.start();
t3.start();
}
public void run(){
System.out.println(Thread.currentThread().getName() + " is running.");
}
}
Output:
The following sample program shows the use of sleep (), join (), and is Alive ().
public class ThreadDemo extends Thread {
public static void main(String[] args) {
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
t1.start();
//starts 2nd thread after 2 sec or if it’s dead
try {
t1.join(2000);
}
catch(InterruptedException e) {
e.printStackTrace();
}
t2.start();
//waits for the threads to terminate
try {
t1.join();
t2.join();
}
catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread-0 is alive: " + t1.isAlive() );
System.out.println("Thread-1 is alive: " + t2.isAlive() );
}
public void run() {
System.out.println(Thread.currentThread().getName() + " is running.");
try {
Thread.sleep(3000); //suspends thread for 3 seconds
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " has ended.");
}
}
Output: