Q1. Defind a thread. List the various method to create a thread. Explain any one method?
Ans. Thread : A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class.Methods to Create a Thread: There are two ways to create a thread :
1. Using Extending Thread Class :
To create a thread, a class provide constructors and methods to create and perform operations on a thread. To implement this method we need to follow two simple steps:Step 1: We need to run override run() method available in thread class. It acts as an entry point for the thread and will puts complete logic inside this method.
Syntax : public void run()
Step 2: Once thread object is created, we can start it by calling start () method, which executes a call to run() method.
Syntax : void start ();
For example:
package com.myjaya. threads;
class MySmp Thread extends Thread{
public static int myCount = 0;
public void run () {
while (MySmpThread.myCount <= 10) {
try {
System.out.println("Expl Thread:"+(++MySmpThread.myCount»);
Thread.sleep (100);
} catch (InterruptedException iex)
System.out.println("Exception in thread: "+iex.getMessage());
}}
}}
public class RunThread {
public static void main(String a [] ) {
System.out.println("Starting Main Thread ...");
MySmpThread mst = newMySmpThread();
mst.start ();
while (MySmp Thread.myCount <= 10) {
try {
System.out.println("Main Thread: "+(++MySmpThread. myCount));
Thread.sleep (100);
} catch (InterruptedException iex) {
System.out.println("Exception in main thread: "+iex.getMessage());
}}
System.out.println("End of Main Thread ..."};
}}
Output:
Starting Main Thread ...Main Thread: 1
Expl Thread: 2
Expl Thread: 3
Main Thread: 4
Expl Thread: 5
Main Thread: 5
Expl Thread: 6
Main Thread: 7
Main Thread: 8
Expl Thread: 9
Expl Thread: 11
Main Thread: 10
End of Main Thread ...
2. By Implementing Runnable Interface:
A thread can be created by extending thread class also. But lava allows only one class to extend, it won't allow multiple inheritance. So, it is always better to create a thread by implementing runnable interface. Java allows you to implement multiple mterfaces at a time. By implementing runnable interface,• We need to provide implementation for run() method.
• To run this implementation class, create a thread object, pass runnable implementation class object to its constructor. Call start() method on thread class to start executing run() method.
• Implementing runnable interface does not create a thread object, it only defines an entry point for threads in your object. It allows you to pass the object to the thread (runnable implementation) constructor.
For example:
package com.myjava.threads;
class MyRunnableThread implements Runnable {
public static int myCount = 0;
public MyRunnableThread () {
}
public void run () {
while (MyRunnableThread.myCount <= 10) {
try{
System.out.println("Expl Thread: "+(++MyRunnableThread. myCount));
Thread.sleep (100);
} catch (InterruptedException iex)
System.out.println("Exception in thread: "+iex.get Message());
}}
}}
public class RunMyThread {
public static void main (String a [ ] ) {
System.out.println("Starting Main Thread ...");
MyRunnableThread mrt = newMyRunnableThread();
Thread t = new Thread (mrt) ;
t.start();
while (MyRunnableThread.myCount <= 10) {
try {
System.out.println("Main Thread: "+ (++MyRunnableThread.myCount));
Thread.sleep (100);
} catch (InterruptedException iex) {
System.out.println("Exception in main thread: "+iex. getMessage());
}
System.out.println("End of Main Thread ...");
}}
Output:
Starting Main Thread ...Main Thread: 1
Expl Thread: 2
Main Thread: 3
Expl Thread: 4
Main Thread: 5
Expl Thread: 6
Main Thread: 7
Expl Thread: 8
Main Thread: 9
Expl Thread: 10
Main Thread: 11
End of Main Thread ...
Q2. Describe thread priorities and synchronisation. Mention the associated methods and describe them briefly?
Ans. In Java programming, priorities and synchronisation are one of the most important features due to its support for multithreading.Thread Priorities :
In Java, each thread is assigned a priority, which affects the order in which it is scheduled for running. Default priority of a thread is 5 (NORM PRIORITY). The value of MIN PRIORITY is 1 and the value of MAX PRIORITY is 10. These thread priorities are used by the thread scheduler to decide when each thread should be allowed to run.Method of Thread's Priority:
To use the thread's priority, use the set Priority () method. In general form,Image
You can also obtain the current priority setting by calling the method; get Priority ()
For example:
import java.lang.*;
public class ThreadDemo {
public class ThreadDemo implements Runnable {.
Thread t;
ThreadDemo () {
t = new Thread (this, "Admin Thread"); //thread created
t.setPriority (1); //set thread priority
System.out.println("thread =" + t); //print thread created
t.start();
}
public void run() {
System.out.println("Thread priority =" + t.getPriority ()); // returns this thread's priority
}
public static void main(String args[]) {
new Thread Demo ();
}}
Thread Synchronisation :
This process is introduce for thread contention, which occurs when two or more threads try to access the same resource simultaneously and cause the Java runtime to execute one or more threads more slowly, or even suspend their execution. It is the ability to control the access of multiple threads to any shared resource.Method of Synchronisation :
This synchronised method, is used to lock for any shared resource. When a thread invokes a synchronised method, it automatically acquire the lock for that object and releases it when the thread completes its task.Let us understand the concept of synchronised with the help of function:
class Table {
synchronised void printTable (int n) { // synchronised method
for (int i = 1; i=5; i++) {
System.out.println(n*i);
try {
Thread.sleep (400);
} catch (Exception e) {System.out.println(e); }
} } }
class MyThreadlextends Thread {
Table t;
MyThreadl (Table t) {
this.t=t;
}
public void run() {
t.print Table (5);
} }
class MyThread2extends Thread {
Table t;
myThread2 (Table t) {
this.t=t;
}
public void run() {
t.printTable (100);
} }
public class TestSynchronisation2 {
public static void main(String args[]) {
Table obj = new Table (; //only one object
My Thread1 t1 = new My Thread1 (obj);
My Thread2 t2 = new My Thread2 (obj);
t1.start();
t2.start();
} }
Join us on Facebook and Twitter to get the latest study material. You can also ask us any questions.
Facebook = @ studywow
(click on it or search "studywow" on facebook)
Twitter = @ studywow
(click on it or search "studywow" on Twitter)
Email= studywow.com@gmail.com
Send us your query anytime!
abcdhttp://ranaji.atwebpages.com/