Definition- Multithreading is a concept of execution of multiple threads, simultaneously.

Process-A process is running state of instruction.
Thread-Threads exist within a process.
every process has at least one thread in it.
Threads share the process’s resources,

Life Cycle of Thread-

·         New

·         Runnable

·         Running

·         Blocked

·         Terminated

thrds

1-New: A Thread begins its life cycle in the new state. It remains in this state until the program starts the thread with start () method. It is also referred to as a born thread.

2.    Runnable: After invoking the start () method on a newly born thread, It enter into the Runnable Pool. In this Runnable Pool the thread scheduler has not selected it to be the running thread. We can have a lot of thread objects in this pool.

Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs 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.

3.    Running: The thread is in running state if the thread scheduler has selected it.

4.    Waiting or blocked: This is the state when the thread is still alive, but is currently not eligible to run as the thread cycles are released from this thread and some higher priority thread is running. We can say that a thread is waiting for its turn in waiting state for its turn.

5.    Terminated: A Runnable thread enters the terminated state when it completes its task and we know that a Thread terminates when there is no code left in the “run ()” method.

THREAD PRIORITY-

Threads with higher priority should be executed before lower-priority threads.
However, thread priorities cannot guarantee the order.

[Static fields]-
Java thread priorities are in the range between
1-MIN_PRIORITY (a constant of 1) and
2-MAX_PRIORITY (a constant of 10).
3-NORM_PRIORITY (a constant of 5)-By default.

Thread creation-

1- Using inheritance (extending thread class)

2-   Using association (implementing runnable interface)

Q- which is better way?
A- Implementing Runnable is the preferred way to do it, that means association is the better way to go.

1) Using inheritance:

Note-
1- Always keep a separate class to start a main thread.

2- If you want to perform different task on a different thread then always keep a separate thread class for each task.

3- If you want to perform a common task on each thread then create a single thread class and make a multiple objects of same thread.

Example-

class Thread1 extends Thread {

public void run()

{
for(int i=0; i<=5; i++)
{
System.out.println(Thread.currentThread().getName());
}
}
}

class Thread2 extends Thread {
public void run()
{
for(int i=0; i<=6; i++)
{
System.out.println(Thread.currentThread().getName());
}
}
}

class RunThread
{
public static void main(String[] Arg)
{

Thread1 t1 = new Thread1();

Thread2 t2 = new Thread2();

t1.start();

t2.start();
}
}

2 )Using Association:
implement Runnable and override the run method.

Example:

class Thread1 implements Runnable{

public void run() {

for(int i=0; i<=10; i++) {

System.out.println(Thread.currentThread().getName());

}

}

}

class RunThread
{
public static void main(String[] args)
{

Thread1 t1 = new Thread1();

Thread tt1 = new Thread(t1);

tt1.start();

Thread tt2 = new Thread(t1);

tt2.start();

}
}

Constructors in Thread class

There are 8 constructors in Thread class:

1.    Thread() : Thread will get default name given by the JVM.

2.    Thread(String s) : Thread will get user specified name.

3.    Thread(Runnable r) : Passing Runnable object to the thread. So the class whose reference is passed, the run of the same class will run.

4.    Thread(Runnable r, String s) : same as last but user specified name is passed here as String type of argument.

5.    Thread(ThreadGroup tg, Runnable r) : passing thread groups to the thread argument.

6.    Thread(ThreadGroup tg, Runnable r, String name) : same as last but user specified name here as String type of argument.

7-Thread(ThreadGroup tg, Runnable r, String name, long stackSize) : same as above, has specified stack size

8-Thread(ThreadGroup group, String s)

Static Methods of Thread Class-

.            sleep(long milliseconds)

.            sleep(long milliseconds, int nanoseconds)

.            yield()

.            currentThread()

.            interrupted ()

.            activeCount()

Instance methods-

·         Public void setName()

·         Public void getName()

·         Public void setPriority()

·         Public void getPriority()

·         Public void join()

·         Public void join(int millisec)

·         Public void setDaemon(Boolean b)

·         Public void interrupt()

·         Public void isInterrupted()

·         Public void isAlive()

.         start()

.          run()

java-runnable-interface-methods.png

.Can we start a thread twice?
->No. After staring a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. For Example:
T1.start();
T1.start(); (exception)

1- Setting and getting name of thread using thread constructor-Thread(runnable object, String name)

To get thread name- “Thread.currentThread().getName()” is used.where

Thread – is a class

currentThread()- is static method

getName()-non static method


package multithreadingCodes;

public class NaminThrd implements Runnable {

@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}

public static void main(String[] args) {
NaminThrd n1 = new NaminThrd();

Thread t1 = new Thread(n1, "abc");
Thread t2 = new Thread(n1, "xyz");

t1.start();
t2.start();

}
}

2- Setting and getting name of thread using setName() method-


package multithreadingCodes;

public class NaminThrd1 implements Runnable {

@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}

public static void main(String[] args) {
NaminThrd1 n1 = new NaminThrd1();

Thread t1 = new Thread(n1);
Thread t2 = new Thread(n1);

t1.setName("abc");
t2.setName("xyz");
t1.start();
t2.start();

}

}

3- Setting and getting priority of threads

package multithreadingCodes;

public class PrityThrd implements Runnable {

@Override
public void run() {
System.out.println(Thread.currentThread().getPriority());
}

public static void main(String[] args){
PrityThrd n1 = new PrityThrd();

Thread t1 = new Thread(n1);
Thread t2 = new Thread(n1);

t1.setPriority(1);
t2.setPriority(10);

t1.start();
t2.start();

}
}

4- sleep method example-

package multithreadingCodes;

public class Sp1 implements Runnable {

@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is sleeping");
try {
Thread.sleep(900);
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName() + " is awake");
}

public static void main(String[] args) throws InterruptedException {
Sp1 s = new Sp1();

Thread thread = new Thread(s);
Thread thread1 = new Thread(s);
Thread thread2 = new Thread(s);

thread.start();
thread1.start();
thread2.start();
}
}

5- join method example

package multithreadingCodes;

public class Jo1 implements Runnable {

@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}

public static void main(String[] args) throws InterruptedException {
System.out.println(Thread.currentThread().getName());

Jo1 j = new Jo1();

Thread thread = new Thread(j);
Thread thread1 = new Thread(j);
Thread thread2 = new Thread(j);

thread.start();
thread.join();

thread1.start();
thread1.join();

thread2.start();
thread2.join();
}
}

6- Yield method example

package multithreadingCodes;

public class Exyld implements Runnable {

@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " " + "started");
Thread.yield();
System.out.println(Thread.currentThread().getName() + " " + "terminated");
}

public static void main(String[] args) throws InterruptedException {
Exyld j = new Exyld();

Thread thread = new Thread(j);
Thread thread1 = new Thread(j);
Thread thread2 = new Thread(j);

thread.start();
thread1.start();
thread2.start();
}
}

123

Synchronization in java –

Synchronization- It’s a capability of control the access of multiple threads to any shared resource.

Types of thread synchronization-

sync

Mutual Exclusion in threads-

It’s concept where threads don’t interfere with one another while sharing data.

Concept of Lock in java-

Synchronized is done around the concept of locks.

Objects have internal entity which is called monitors.

Threads can lock and unlock these monitors.

One object can hold only one lock.

One thread can hold many locks

1- Synchronized method example-


package multithreadingCodes;

class Ex {
synchronized void show() {
for(int i=0; i<5;i++)
System.out.println(Thread.currentThread().getName()+" working");
}
}

public class syncMeth implements Runnable {
Ex ex = new Ex();

@Override
public void run() {
ex.show();
}

public static void main(String[] args) {
syncMeth meth = new syncMeth();

Thread thread = new Thread(meth);
Thread thread1 = new Thread(meth);

thread.start();
thread1.start();
}
}

2- Synchronized block example


package multithreadingCodes;

class Ex1 {
void show() {
System.out.println("random" + Thread.currentThread().getName());
synchronized (this) {
System.out.println("starting " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println("sleeping " + Thread.currentThread().getName());
}
}
}

public class SyncBlock implements Runnable {
Ex1 ex = new Ex1();

@Override
public void run() {
ex.show();
}

public static void main(String[] args) {
SyncBlock blk = new SyncBlock();

Thread thread = new Thread(blk);
Thread thread1 = new Thread(blk);

thread.start();
thread1.start();
}
}

3-Static Synchronization example-


package multithreadingCodes;

class Ex2{
synchronized static void show(){
System.out.println("starting "+Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println("sleeping "+Thread.currentThread().getName());
}
}

public class syncstaticMeth implements Runnable {
Ex2 ex=new Ex2();
@Override
public void run() {

ex.show();
}

public static void main(String[] args) {
syncstaticMeth meth=new syncstaticMeth();
syncstaticMeth meth2=new syncstaticMeth();

Thread thread=new Thread(meth);
Thread thread1=new Thread(meth2);

thread.start();
thread1.start();
}
}

Advertisements