Showing posts with label thread sleep. Show all posts
Showing posts with label thread sleep. Show all posts

Saturday, 1 March 2014

synchronization

Synchronization is a process of orderly sharing of system resources

Will explore the need of synchronization and how to use it in java with an example.

Problem Description:
I have 2 threads want to print data from 0 to 4 in orderly. Like (0 1 2 3 4 0 1 2 3 4)

Solution without synchronization
class PrintWithOutSynch implements Runnable{
 public void run(){
  print1to10();
 }

 void print1to10(){
  for(int i=0; i < 10; i++){
   System.out.println(i);
   try{
    Thread.currentThread().sleep(1000);
   }
   catch(InterruptedException e){
   }
  }
 }

 public static void main(String args[]){
  PrintWithOutSynch task1 = new PrintWithOutSynch();
  Thread t1 = new Thread(task1);
  Thread t2 = new Thread(task1);
  t1.start();
  t2.start();
 }
}
    
Output
0 0 1 1 2 2 3 3 4 4

But we are expecting output like 0 1 2 3 4 0 1 2 3 4.

So what is wrong with this approach
Since threads are independent, both threads works parallel. If thread1 enters into sleep, thread2 has a chance to run, if thread2 enters into sleep, thread1 has a chance to run.

How to solve the problem
Make the print method as synchronized, if a method declared as synchronized, then at a time only one thread can enters into the synchronized method of a particular object(here for task1 object). Remaining threads wait until the thread which enters into the synchronized method finishes its execution or releases the lock voluntarily.

Solution with Synchronization
class PrintWithOutSynch implements Runnable{
 public void run(){
  print1to10();
 }

 synchronized void print1to10(){
  for(int i=0; i < 5; i++){
   System.out.print(i +" ");
   try{
    Thread.currentThread().sleep(1000);
   }
   catch(InterruptedException e){
   }
  }
 }

 public static void main(String args[]){
  PrintWithOutSynch task1 = new PrintWithOutSynch();
  Thread t1 = new Thread(task1);
  Thread t2 = new Thread(task1);
  t1.start();
  t2.start();
 }
}
   
Output

0 1 2 3 4 0 1 2 3 4


volatile keyword                                                 Synchronized methods                                                 Home

Giving Up the Processor : yield()

Generally higher priority threads get more processor time than low priority threads.

When a low priority thread is running, and a high priority thread came to the ready queue, then Scheduler swaps the low priority thread from Running state and make the processor available for the high priority thread.
If you have a high priority thread which is doing long running operations, then there is a way in java, to voluntarily Relinquishing the Processor for some time.

Signature
public static void yield()

Causes the currently executing thread object to temporarily pause and allow other threads to execute. This is a static method, so we can call it by using class name.

Example
class ThreadYield implements Runnable{
 public void run(){
  for(int i=0; i< 10; i++){
   System.out.println(Thread.currentThread().getName() +"\t" + i);
  }
 }

 public static void main(String args[]){
  ThreadYield task1 = new ThreadYield();
  ThreadYield task2 = new ThreadYield();

  Thread t1 = new Thread(task1);
  Thread t2 = new Thread(task2);

  t1.setName("High Priority Thread");
  t2.setName("Low Priority Thread");

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

  t1.start();
  t2.start();
 }
}
   
sample Output1
High Priority Thread 0
High Priority Thread 1
High Priority Thread 2
High Priority Thread 3
High Priority Thread 4
High Priority Thread 5
High Priority Thread 6
High Priority Thread 7
High Priority Thread 8
High Priority Thread 9
Low Priority Thread 0
Low Priority Thread 1
Low Priority Thread 2
Low Priority Thread 3
Low Priority Thread 4
Low Priority Thread 5
Low Priority Thread 6
Low Priority Thread 7
Low Priority Thread 8
Low Priority Thread 9

Some points to remember
1. just like sleep(), yield() also doesn't release the lock.

Example
class ThreadYield implements Runnable{
 static Object obj = new Object();

 public void run(){
  synchronized(obj){
   for(int i=0; i< 10; i++){
    System.out.println(Thread.currentThread().getName() +"\t" + i);
    Thread.currentThread().yield();
   }
  }
 }

 public static void main(String args[]){
  ThreadYield task1 = new ThreadYield();
  Thread t1 = new Thread(task1);
  Thread t2 = new Thread(task1);

  t1.setName("Thread 1");
  t2.setName("Thread 2");

  t1.start();
  t2.start();
 }
}
    
Sample Output

Thread 1 0
Thread 1 1
Thread 1 2
Thread 1 3
Thread 1 4
Thread 1 5
Thread 1 6
Thread 1 7
Thread 1 8
Thread 1 9
Thread 2 0
Thread 2 1
Thread 2 2
Thread 2 3
Thread 2 4
Thread 2 5
Thread 2 6
Thread 2 7
Thread 2 8
Thread 2 9

Thread Priority                                                 volaite keyword                                                 Home