Page 373 - CITS - Computer Software Application -TT
P. 373
COMPUTER SOFTWARE APPLICATION - CITS
If you are not extending the Thread class, your class object would not be treated as a thread object. So you need
to explicitly create the Thread class object. We are passing the object of your class that implements Runnable so
that your class run() method may execute.
3 Using the Thread Class: Thread(String Name)
We can directly use the Thread class to spawn new threads using the constructors defined above.
FileName: MyThread1.java
public class MyThread1
{
// Main method
public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor Thread(String name)
Thread t= new Thread(“My first thread”);
// the start() method moves the thread to the active state
t.start();
// getting the thread name by invoking the getName() method
String str = t.getName();
System.out.println(str);
}
}
Output
My first thread
4 Using the Thread Class: Thread(Runnable r, String name)
Observe the following program.
FileName: MyThread2.java
public class MyThread2 implements Runnable
{
public void run()
{
System.out.println(“Now the thread is running ...”);
}
// main method
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();
// creating an object of the class Thread using Thread(Runnable r, String name)
360
CITS : IT&ITES - Computer Software Application - Lesson 101 - 108