February 21, 2014

Java Threads

Java Synchronized

public class MyClass {
  
    public synchronized void log1(String msg1, String msg2){
       log.writeln(msg1);
       log.writeln(msg2);
    }

  
    public void log2(String msg1, String msg2){
       synchronized(this){
          log.writeln(msg1);
          log.writeln(msg2);
       }
    }
  } 
 
 
Only one thread can execute inside a Java code block synchronized on the same monitor object.
The following two examples are both synchronized on the instance they are called on. They are therefore equivalent with respect to synchronization:
Thus only a single thread can execute inside either of the two synchronized blocks in this example.

public class Counter{

  private static int count = 0;

  public synchronized int getCount(){
    return count;
  }

  public synchronized setCount(int count){
     this.count = count;
  }

}// only either will be run by any thread

==================
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package
.
================
final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
==============
 

 

No comments:

Post a Comment