Multithreading & Synchronization
Multithreading & Synchronization
Thread:
A thread is a piece of code that executes independently.
Every program contains at least one thread. i.e. main thread
Main thread default name is main only.
Main thread default priority is normal priority(Priority number is 5)
}catch(Exception e)
{
System.err.println(e);
}
}
}
}
Example:
class Demo extends Thread
{
public void run()
{
try{
for(int i=1;i<=10;i++)
{
System.out.println("Child Thread: "+i);
Thread.sleep(1000);
}
}catch(Exception e)
{
System.err.println(e);
}
}
public static void main(String args[])
{
try{
Demo d=new Demo();
d.start();
for(int i=1;i<=10;i++)
{
System.out.println("Main Thread: "+i);
Thread.sleep(1000);
if(i==5)
d.suspend();
if(i==10)
d.resume();
}
}catch(Exception e)
{
System.err.println(e);
}
}
}
Example:
class Test implements Runnable
{
public void run()
{
try{
for(int i=1;i<=10;i++)
{
System.out.println("JavaEE");
Thread.sleep(1000);
}
}catch(Exception e)
{
System.err.println(e);
}
}
}
class Demo implements Runnable
{
public void run()
{
try{
for(int i=1;i<=10;i++)
{
System.out.println("Core Java");
Thread.sleep(2000);
}
}catch(Exception e)
{
System.err.println(e);
}
}
Synchronization:
It is a mechanism that allows to access a shared resource only one thread at a
time.
There are two ways to synchronize the code:
1) synchronizing a method
1) synchronizing a method:
Syntax:
synchronized ReturnType MethodName(arg1, arg2, ......)
{
================
================
================
}
Example:
class Bank
{
float balance=5000.00f;
synchronized void withdraw(float amount)
{
try{
System.out.println("Withdraw Started");
if(balance<amount)
{
System.out.println("Less Balance, Waiting for Deposit");
wait();
}
balance=balance-amount;
System.out.println("Withdraw Completed");
}catch(Exception e)
{
System.err.println(e);
}
}
synchronized void deposit(float amount)
{
System.out.println("Deposit Started");
balance=balance+amount;
System.out.println("Deposit Completed");
notify();
}
}
class Customer1 extends Thread
{
Bank b;
Customer1(Bank b)
{
this.b=b;
}
public void run()
{
b.withdraw(8000.00f);
}
}
class Customer2 extends Thread
{
Bank b;
Customer2(Bank b)
{
this.b=b;
}
public void run()
{
b.deposit(5000.00f);
}
}
class Demo
{
public static void main(String args[])
{
Bank b=new Bank();
Customer1 c1=new Customer1(b);
c1.start();
Customer2 c2=new Customer2(b);
c2.start();
}
}