0% found this document useful (0 votes)
5 views

Threads

Important questions

Uploaded by

krakshit2006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Threads

Important questions

Uploaded by

krakshit2006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

INFORMATION TECHNOLOGY

CLASS-12
Threads
1. Define Threads
A multithreaded program consists of two or more parts called threads each of which can execute a
different task independently at the same time. In Java, threads can be created in two ways
1. By extending the Thread class
2. By implementing the Runnable interface
2. How threads can be created in Java? Explain with example
In Java, threads can be created in two ways
1. By extending the Thread class
public class ExtendThread extends Thread {
public void run() {
System.out.println("Created a Thread");
for (int count = 1; count <= 3; count++)
System.out.println("Count="+count);
}
}
public static void main(String args[]) {
ExtendThread t1 =new ExtendThread();
t1.start();
}

2. By implementing the Runnable interface


public class RunnableDemoimplements Runnable {
public void run() {
System.out.println("Created a Thread");
for (int count = 1; count <= 3; count++)
System.out.println("Count="+count);
}

}
public static void main(String args[]){

RunnableDemo r = new RunnableDemo();

Thread t1 = new Thread(r);

t1.start();

3. Define run method of Thread class.

The run() method is the entry point for every new thread that is instantiated from the class.
4. Define start method of Thread class.
The start() method is invoked to start the execution of thread.
5. What is the difference between creating thread by extending the Thread class and by
implementing Runnable interface.
Classes that you create by extending the Thread class cannot be extended further. However,
Implementing the Runnable interface gives the flexibility to extend classes created by this method.

You might also like