Thread

Definition of Synchronized

Synchronized block in java are marked with the synchronized keywork. All synchronized blocks synchronized on the same object can only have one thread executing inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block

The use of thread in Java

Threads allows a program to operate more more efficiently by doing multiple things at the smae time.

Threads can be used to perform complicated tasks in the baackground without interrupting the main program.

线程同步概念

当一个线程对一块内存进行操作的时候,其他的线程都不可以对这块内存进行操作,直到该线程操作完毕,其他线程才可以对其进行操作。

多个线程访问同一个资源会产生线程安全问题,所以要进行加锁

 // A Java program to demonstrate working of
 // synchronized.
 import java.io.*;
 import java.util.*;
 
 // A Class used to send a message
 class Sender
 {
     public void send(String msg)
    {
         System.out.println("Sending\t"  + msg );
         try
        {
             Thread.sleep(1000);
        }
         catch (Exception e)
        {
             System.out.println("Thread interrupted.");
        }
         System.out.println("\n" + msg + "Sent");
    }
 }
 
 // Class for send a message using Threads
 class ThreadedSend extends Thread
 {
     private String msg;
     Sender  sender;
 
     // Receives a message object and a string
     // message to be sent
     ThreadedSend(String m,  Sender obj)
    {
         msg = m;
         sender = obj;
    }
 
     public void run()
    {
         // Only one thread can send a message
         // at a time.
         synchronized(sender)
        {
             // synchronizing the snd object
             sender.send(msg);
        }
    }
 }
 
 // Driver class
 class SyncDemo
 {
     public static void main(String args[])
    {
         Sender snd = new Sender();
         ThreadedSend S1 =
             new ThreadedSend( " Hi " , snd );
         ThreadedSend S2 =
             new ThreadedSend( " Bye " , snd );
 
         // Start two threads of ThreadedSend type
         S1.start();
         S2.start();
 
         // wait for threads to end
         try
        {
             S1.join();
             S2.join();
        }
         catch(Exception e)
        {
             System.out.println("Interrupted");
        }
    }
 }

Output:

 Sending     Hi 
 Hi Sent
 ​
 Sending     Bye
 Bye Sent

In the above example, we chose to synchronize the Sender object inside the run() method of the ThreadedSend class. Alternately, we could define the whole send() block as synchronized and it would produce the same result. Then we don’t have to synchronize the Message object inside the run() method in ThreadedSend class.

 

 

A locak is a thread synchronization mehcanism like synchonized blocks except locaks can be more sophisticated than Java's synchronized blocks. Locks are created using synchronized blocks, so it is no like we can get totally rid of the synchronized keyword

Differences Between Lock and Synchronized Block

There are few differences between the use of synchronized bock and using Lock API's

  • A sysnchronized block is fully contained within a method

  • A synchronized block doesn't support the fairness, any thread can acquire the locak once released, no preference can be specified. We can achieve fairness within the Lock APIs by specifying the fairness property

  • A thread gets blocked if it can't get an access to the synchronized block. The *Lock* API provides *tryLock()* method. The thread acquires lock only if it's available and not held by any other thread.

  • A thread which is in “waiting” state to acquire the access to synchronized block, can't be interrupted. The *Lock* API provides a method *lockInterruptibly()* which can be used to interrupt the thread when it's waiting for the lock

Lock API

  • void locak()

  • void lockInterruptibly()

  • boolean tryLock()

  • boolean tryLock(long timeout, TimeUnit timeUnit)

  • void unlock()

 
 
 
Thread

Definition of Synchronized

Synchronized block in java are marked with the synchronized keywork. All synchronized blocks synchronized on the same object can only have one thread executing inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block

The use of thread in Java

Threads allows a program to operate more more efficiently by doing multiple things at the smae time.

Threads can be used to perform complicated tasks in the baackground without interrupting the main program.

线程同步概念

当一个线程对一块内存进行操作的时候,其他的线程都不可以对这块内存进行操作,直到该线程操作完毕,其他线程才可以对其进行操作。

多个线程访问同一个资源会产生线程安全问题,所以要进行加锁

 // A Java program to demonstrate working of
 // synchronized.
 import java.io.*;
 import java.util.*;
 
 // A Class used to send a message
 class Sender
 {
     public void send(String msg)
    {
         System.out.println("Sending\t"  + msg );
         try
        {
             Thread.sleep(1000);
        }
         catch (Exception e)
        {
             System.out.println("Thread interrupted.");
        }
         System.out.println("\n" + msg + "Sent");
    }
 }
 
 // Class for send a message using Threads
 class ThreadedSend extends Thread
 {
     private String msg;
     Sender  sender;
 
     // Receives a message object and a string
     // message to be sent
     ThreadedSend(String m,  Sender obj)
    {
         msg = m;
         sender = obj;
    }
 
     public void run()
    {
         // Only one thread can send a message
         // at a time.
         synchronized(sender)
        {
             // synchronizing the snd object
             sender.send(msg);
        }
    }
 }
 
 // Driver class
 class SyncDemo
 {
     public static void main(String args[])
    {
         Sender snd = new Sender();
         ThreadedSend S1 =
             new ThreadedSend( " Hi " , snd );
         ThreadedSend S2 =
             new ThreadedSend( " Bye " , snd );
 
         // Start two threads of ThreadedSend type
         S1.start();
         S2.start();
 
         // wait for threads to end
         try
        {
             S1.join();
             S2.join();
        }
         catch(Exception e)
        {
             System.out.println("Interrupted");
        }
    }
 }

Output:

 Sending     Hi 
 Hi Sent
 ​
 Sending     Bye
 Bye Sent

In the above example, we chose to synchronize the Sender object inside the run() method of the ThreadedSend class. Alternately, we could define the whole send() block as synchronized and it would produce the same result. Then we don’t have to synchronize the Message object inside the run() method in ThreadedSend class.

 

 

A locak is a thread synchronization mehcanism like synchonized blocks except locaks can be more sophisticated than Java's synchronized blocks. Locks are created using synchronized blocks, so it is no like we can get totally rid of the synchronized keyword

Differences Between Lock and Synchronized Block

There are few differences between the use of synchronized bock and using Lock API's

  • A sysnchronized block is fully contained within a method

  • A synchronized block doesn't support the fairness, any thread can acquire the locak once released, no preference can be specified. We can achieve fairness within the Lock APIs by specifying the fairness property

  • A thread gets blocked if it can't get an access to the synchronized block. The *Lock* API provides *tryLock()* method. The thread acquires lock only if it's available and not held by any other thread.

  • A thread which is in “waiting” state to acquire the access to synchronized block, can't be interrupted. The *Lock* API provides a method *lockInterruptibly()* which can be used to interrupt the thread when it's waiting for the lock

Lock API

  • void locak()

  • void lockInterruptibly()

  • boolean tryLock()

  • boolean tryLock(long timeout, TimeUnit timeUnit)

  • void unlock()