Multitasking is a process of executing one or more tasks concurrently or at a time. Similarly, multithreading is the process of executing one or more threads at the same time or concurrently.
Multitasking can be implanting in two ways:
Multiprocessing
Multithreading
Multiprocessing | Multithreading |
---|---|
|
|
|
|
|
|
|
|
package com.javabykiran.Thread;
/**
* @author Java By Kiran
*/
public class Lab1 {
public static void main(String[] args) {
System.out.println("main begin");
Thread t = Thread.currentThread();
System.out.println(t);
System.out.println(t.getName());
System.out.println(t.getPriority());
t.setName("JAVABYKIRAN");
t.setPriority(9);
System.out.println(t);
System.out.println(t.getName());
System.out.println(t.getPriority());
System.out.println("main end");
}
}
Output:
main begin
Thread[main,5,main]
main
5
Thread[JAVABYKIRAN,9,main]
JAVABYKIRAN
9
main end
When we try to run any class
We need keep in mind the following: whenever main method get call automatically
public static void main (String [] args) {}
Take the class name
Take the command line value
Creates the String array object
If command line value is there then it stores command line value in String array
Create the Thread group with name main
Creates the Thread with :
Starts the main thread
Listed below are a few points that must be noted:
By default, JVM is created the main thread and is started, which is responsible for invoking the main method.
You can write your own threads which are called by user defined threads and are called as child threads.
You can also implement code for required tasks in the child threads.
The JVM always starts the main method and all child threads will also start from the main thread
You can develop user defined threads in two way:
package com.javabykiran.thread;
public class ThreadOne extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
// Displaying the numbers from this thread
System.out.println("Running First Thread : " + i);
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
}
}
package com.javabykiran.thread;
public class ThreadTwo extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Running Second Thread : " + i);
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
}
}
package com.javabykiran.thread;
public class ThreadTest {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + " Thread Begin...");
ThreadOne firstThread = new ThreadOne();
ThreadTwo secondThread = new ThreadTwo();
firstThread.start();
secondThread.start();
}
}
Output:
main Thread Begin...
Running First Thread : 1
Running Second Thread : 1
Running Second Thread : 2
Running First Thread : 2
Running Second Thread : 3
Running Second Thread : 4
Running First Thread : 3
Running Second Thread : 5
Running First Thread : 4
Running First Thread : 5
package com.javabykiran.Thread;
/**
* @author Java By Kiran
*/
public class Stack {
int x;
void push(int a) {
x = a;
}
int pop() {
return x;
}
}
package com.javabykiran.Thread;
/**
* @author Java By Kiran
*/
public class ThreadsA implements Runnable {
Stack st = null;
public ThreadsA(Stack st, String tname) {
Thread t = new Thread(this, tname);
this.st = st;
t.start();
}
public void run() {
for (int i = 1; i <= 5; i++) {
st.push(i);
System.out.println(i + " is pushed by A");
try {
Thread.sleep(500);
} catch(Exception e) {
}
}
}
}
package com.javabykiran.Thread;
/**
* @author Java By Kiran
*/
public class ThreadsB extends Thread {
Stack st = null;
public ThreadsB(Stack st, String tname) {
super(tname);
this.st = st;
start();
}
public void run() {
for (int i = 1; i <= 5; i++) {
int x = st.pop();
System.out.println(x + " is poped by B");
Try {
Thread.sleep(500);
} catch (Exception e) {
}
}
}
}
package com.javabykiran.Thread;
/**
* @author Java By Kiran
*/
public class Lab3 {
public static void main(String[] args) {
Stack st = new Stack();
ThreadsA a = new ThreadsA(st, "A");
ThreadsB a1 = new ThreadsB(st, "B");
for (int i = 1; i <= 5; i++) {
System.out.println(i+"by"+Thread.currentThread().getName());
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
}
}
Extending thread | Implementing Runnable |
---|---|
Your user defined thread class has to extend java.lang.Thread | Your user defined thread class has to implement java.lang.Runnable |
From your thread class, you can invoke the following threads class constructors: Thread (string) and Thread (Thread Group, string). | When your thread class is implementing Runnable interface, you have to explicitly create the thread with one of the following constructors:
|
Example:
|
Example:
|
When you create and start the thread, it will be placed in a ready to run state, and the thread will just wait for the CPU → start()
When the CPU scheduler allocates the CPU for them, t thread will be placed in running and be utilised by the CPU → run()
Depending on the CPU scheduling algorithm, the thread will be moved to ready to run from running state
When you call the sleep() method on the running thread, the thread will go into a sleep state and stay in that sleep state for a specified amount of time. Once the time is up, the thread will be moved into a ready to run state automatically
sleep() method will overload with the following version: void sleep(long)
The thread sleeps for specified amount of milliseconds and nano seconds void sleep(long , int)
When you call the wait() method during the running state, the thread will go into the wait state
To move the thread to wait, you can call one of the following methods of object class
Thread waiting is in wait state there until either notify() or notifyAll() is called.
If notify() or notifyAll() is called before the specified amount of time, the thread will be moved to ready to run state
If specified amount of time is over without notifying, the thread will be moved to ready to run state automatically
When you call the notify() method, the thread which has been waiting for a long time in the wait state will be moved into the ready to run state
When you call the notifyAll() method, all the threads which are waiting will be moved to ready to run state
When a thread is waiting for an unavailable resource, the thread will be blocked and placed in blocked state. Later, when the requested resource is available, it will be moved to ready to run state
A blocked state is very dangerous since it may leads to deadlocks
Consider the following scenario: there are threads running concurrently. Call t1 and t2 and hold the resources called r1 and r2 respectively.
What would you do? → class A t1
→ class B t2
package com.javabykiran.Thread;
public class A extends Thread {
@Override
public void run(){
synchronized (String.class) {
// here T1 comes wait for
// somebody to release Integer lock
// but here T1 is already acquired this lock
// so not possible
synchronized (Integer.class) {
System.out.println("I am in A");
}
}
}
}
package com.javabykiran.Thread;
public class B extends Thread {
@Override
public void run() {
synchronized (Integer.class) {
// here T2 comes wait for
// somebody to release String lock
// but here T2 is already acquired this lock
// so not possible
synchronized (String.class) {
System.out.println("I am in B");
}
}
}
}
package com.javabykiran.Thread;
public class DeadLockTest {
public static void main(String[] args) {
A a = new A();
a.setName("A");
a.start();
B b=new B();
b.setName("B");
b.start();
}
}
CPU schedulers are responsible for allocating CPU time for various processes or threads running in system. There FCFS or First Come First Served one is the simplest.
Priority is a number assigned to the thread which will be used by the CPU scheduler to give more preference to the threads.
Yes, you can overload. But JVM calls the run() method whose signature is available in runnable interface i.e. public void run() and other overloaded methods should not be called by the JVM.
Method | Meaning |
---|---|
getName | Obtain a thread's name |
getPriority | Obtain a thread's priority |
isAlive | Determine if a thread is still running |
join | Pause the current thread execution until the specified thread is dead |
run | Entry point for the thread |
sleep | Suspend a thread for a period of time |
start | Start a thread by calling its run method |