Page 372 - CITS - Computer Software Application -TT
P. 372
COMPUTER SOFTWARE APPLICATION - CITS
20 public void interrupt(): interrupts the thread.
21 public boolean isInterrupted(): tests if the thread has been interrupted.
22 public static boolean interrupted(): tests if the current thread has been interrupted.
Runnable interface
The Runnable interface should be implemented by any class whose instances are intended to be executed by a
thread. Runnable interface have only one method named run().
1 public void run(): is used to perform action for a thread.
Starting a thread
The start() method of Thread class is used to start a newly created thread. It performs the following tasks:
- A new thread starts(with new callstack).
- The thread moves from New state to the Runnable state.
- When the thread gets a chance to execute, its target run() method will run.
1 Java Thread Example by extending Thread class
FileName: Multi.java
class Multi extends Thread{
public void run(){
System.out.println(“thread is running...”);
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:
thread is running...
2 Java Thread Example by implementing Runnable interface
FileName: Multi3.java
class Multi3 implements Runnable{
public void run(){
System.out.println(“thread is running...”);
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}
Output:
thread is running...
359
CITS : IT&ITES - Computer Software Application - Lesson 101 - 108