Java Language / Java Threads

It is a light weight process. Program under execution is called as process.

Java Threads

It is created in 2 ways. They were
1. Extending Thread class. 2. Implementing Runnable Interface

Thread Life Cycle
It consists of 5 states. They were

New – New created Thread will be in a new state.
Running - Thread executing will be be in running state.
Suspended - Thread executing can be suspended.
Blocked - Thread executing can be blocked when waiting for a resource.
Terminated - A thread can be terminated will be in terminated state.

Java thread life cycle methods

Program for creating Threads by extending Thread Class and prints its ID. Output

class Multithreads extends Thread
{
public void run()
{
try
{
System.out.println ("Thread Id = " +Thread.currentThread().getId() + " is running");
}
catch (Exception e)
{
System.out.println ("Exception is caught");
}
}
}

public class Multithreadclass
{
public static void main(String[] args)
{
Multithreads object1 = new Multithreads();
object1.start();
Multithreads object2 = new Multithreads();
object2.start();
Multithreads object3 = new Multithreads();
object3.start();
}
}

Thread Id = 21 is running
Thread Id = 22 is running
Thread Id = 23 is running
Program for creating Threads by implementing Runnable Interface and prints its ID. Output

class Multithreads implements Runnable
{
public void run()
{
try
{
System.out.println ("Thread " +Thread.currentThread().getId() +" is running");
}
catch (Exception e)
{
System.out.println ("Exception is caught");
}
}
}

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

Thread object1 = new Thread(new Multithreads());
object1.start();
Thread object2 = new Thread(new Multithreads());
object2.start();
Thread object3 = new Thread(new Multithreads());
object3.start();
}
}

Thread Id = 21 is running
Thread Id = 22 is running
Thread Id = 23 is running

Thread Synchronization
To avoid thread interference and memory consistency error when 2 / more threads shared resource a common resource java Synchronization method is used.

Program for creating Threads by implementing the Runnable Interface and prints its ID. Output

class Table
{
synchronized void printTable
(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e){System.out.println(e);}
}
}
}

class T1 extends Thread
{
Table t;
T1(Table t)
{
public void run()
{
t.printTable(2);
}
}

class T2 extends Thread
{
Table t;
T2(Table t)
{
this.t=t;
}

public void run()
{
t.printTable(9);
}<
}

public class javaSynchronizationclass
{
public static void main(String args[])
{
Table obj = new Table();
T1 t1=new T1(obj);
T2 t2=new T2(obj);
t1.start();
t2.start();
}
}


2

4

6

8

10

9
18

27

36

45



Home     Back