Detailed Java programming thread synchronization and the method of timed start threads _java

Source: Internet
Author: User
Tags prepare rand static class thread logic volatile

The lock is not released when

uses Wait () and notify () to implement inter-thread collaboration
1. Wait () and notify ()/notifyall ()
call sleep () and yield (). and calling Wait () releases the lock. This allows another task (thread) to get the lock on the current object and thus enter its synchronized method. You can resume execution from wait () either through Notify ()/notifyall (), or when the time expires. The
can only call Wait (), notify (), and Notifyall () in a synchronous control method or in a synchronization block. If these methods are invoked in an asynchronous method, the illegalmonitorstateexception exception is thrown at run time.
2. Simulate a single thread's wake-up call to multiple threads
simulate the collaboration between threads. The game class has 2 synchronization methods prepare () and go (). The flag bit start is used to determine if the current thread requires a wait (). An instance of the game class starts all instances of the Athele class first, bringing it into the wait () state, changing the flag bit and Notifyall () all Athele threads in the waiting state after a period of time.
Game.java

package concurrency;
Import java.util.Collection;
Import java.util.Collections;
Import Java.util.HashSet;
Import Java.util.Iterator;

Import Java.util.Set;
  Class Athlete implements Runnable {private final int id;

  Private Game Game;
   Public athlete (int ID, Game Game) {this.id = ID;
  This.game = game; public boolean equals (Object o) {if (!)
   o instanceof athlete) return false;
   Athlete athlete = (athlete) o;
  return id = = Athlete.id;
  Public String toString () {return "athlete<" + ID + ">";
  public int hashcode () {return new Integer (ID). hashcode ();
   public void Run () {try {game.prepare (this);
   catch (Interruptedexception e) {System.out.println (this + "quit the Game");
  }} public class Game implements Runnable {private set<athlete> players = new hashset<athlete> ();

  Private Boolean start = false;
  public void Addplayer (athlete one) {players.add (one); } public void RemovepLayer (athlete one) {players.remove (one);
  Public collection<athlete> Getplayers () {return collections.unmodifiableset (players);
   The public void prepare (athlete athlete) throws Interruptedexception {System.out.println (athlete + "ready!");
    Synchronized (this) {while (!start) wait ();
   if (start) System.out.println (athlete + "go!");
  } public synchronized void Go () {notifyall ();
   public void Ready () {iterator<athlete> iter = getplayers (). iterator ();
  while (Iter.hasnext ()) New Thread (Iter.next ()). Start ();
   public void Run () {start = false;
   System.out.println ("Ready ...");
   System.out.println ("Ready ...");
   System.out.println ("Ready ...");
   Ready ();
   Start = true;
   System.out.println ("go!");
  Go ();
   public static void Main (string[] args) {Game Game = new Game ();
   for (int i = 0; i < i++) Game.addplayer (new athlete (I, game)); New Thread (game). Start ();
  }
}

 

Results:


Ready ...
Ready ...
Ready ... Athlete<0> ready!
Athlete<1> ready!
Athlete<2> ready!
Athlete<3> ready!
Athlete<4> ready!
Athlete<5> ready!
Athlete<6> ready!
Athlete<7> ready!
Athlete<8> ready!
Athlete<9> ready!
Go!
Athlete<9> go!
Athlete<8> go!
Athlete<7> go!
Athlete<6> go!
Athlete<5> go!
Athlete<4> go!
Athlete<3> go!
Athlete<2> go!
Athlete<1> go!
Athlete<0> go!

3. Simulation Busy Waiting process
an instance of the MyObject class is the observed, and when observed, it notifies an instance of the Monitor class (the way to notify is to change a flag bit). The example of this monitor class is to constantly check for changes in flag bits by busy waiting.
Busywaiting.java

Import Java.util.concurrent.TimeUnit;

Class MyObject implements Runnable {
  private monitor monitor;

  Public MyObject (monitor monitor) {
   this.monitor = monitor;
  }

  public void Run () {
   try {
    TimeUnit.SECONDS.sleep (3);
    System.out.println ("I ' m going.");
    Monitor.gotmessage ();
   } catch (Interruptedexception e) {
    e.printstacktrace ();

}}} Class Monitor implements Runnable {
  private volatile Boolean go = false;

  public void Gotmessage () throws Interruptedexception {go
   = true;
  }

  public void watching () {while
   (go = False)
    ;
   System.out.println ("He has gone.");
  }

  public void Run () {
   watching ();
  }
}

public class Busywaiting {public
  static void Main (string[] args) {
   monitor monitor = new monitor ();
   MyObject o = new MyObject (monitor);
   New Thread (O). Start ();
   New Thread (monitor). Start ();


Results:

I ' m going.
He has gone.

4. Use Wait () and notify () to rewrite the above example
The following example replaces the busy wait mechanism by waiting (), and notify the current monitor class thread when a notification message is received.
Wait.java

Package concurrency.wait;

Import Java.util.concurrent.TimeUnit;

Class MyObject implements Runnable {
  private monitor monitor;

  Public MyObject (monitor monitor) {
   this.monitor = monitor;
  }

Timed Start thread
here are two ways to start a thread after a specified time. One is realized through Java.util.concurrent.DelayQueue and the other is realized through Java.util.concurrent.ScheduledThreadPoolExecutor.
1. Java.util.concurrent.DelayQueue
A class delayqueue is a unbounded blocking queue that extracts elements only when the delay expires. It accepts an instance that implements the delayed interface as an element.
<<interface>>delayed.java

Package java.util.concurrent;
Import java.util.*;
Public interface delayed extends Comparable<delayed> {
  long getdelay (timeunit unit);
}

Getdelay () returns the remaining delay time associated with this object, expressed in a given time unit. The implementation of this interface must define a CompareTo method that provides a consistent sort of getdelay method for this interface.

The head of the Delayqueue queue is the delayed element that is saved for the longest time after the delay expires. Expiration occurs when an element's Getdelay (Timeunit.nanoseconds) method returns a value less than or equal to 0.
2. Design a queue with time delay characteristics
class Delayedtasker maintains a delayqueue<delayedtask> queue in which Delayedtask implements the delayed interface and is defined by an internal class. Both the external class and the inner class implement the Runnable interface, and for the outer class its run method is to take out the tasks in the queue in the defined time sequence, which is an instance of the inner class, and the internal class's Run method defines each thread specific logic.

The essence of this design is to define a thread task list with a time attribute, and the list can be of arbitrary length. Specify the start time each time you add a task.
Delayedtasker.java

Package com.zj.timedtask;
Import static Java.util.concurrent.TimeUnit.SECONDS;

Import static Java.util.concurrent.TimeUnit.NANOSECONDS;
Import java.util.Collection;
Import java.util.Collections;
Import Java.util.Random;
Import Java.util.concurrent.DelayQueue;
Import java.util.concurrent.Delayed;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

Import Java.util.concurrent.TimeUnit; public class Delayedtasker implements Runnable {delayqueue<delayedtask> queue = new delayqueue<delayedtask>

  ();
  public void AddTask (Delayedtask e) {queue.put (e);
  public void Removetask () {queue.poll ();
  Public collection<delayedtask> Getalltasks () {return collections.unmodifiablecollection (queue);
  public int gettaskquantity () {return queue.size ();
      public void Run () {while (!queue.isempty ()) try {queue.take (). run (); The catch (Interruptedexception e) {System.out.println ("INterrupted ");
  } System.out.println ("Finished Delayedtask");
    public static class Delayedtask implements delayed, Runnable {private static int counter = 0;
    private final int id = counter++;
    private final int Delta;

    Private final long trigger;
      Public delayedtask (int delayinseconds) {delta = delayinseconds;
    Trigger = System.nanotime () + Nanoseconds.convert (delta, SECONDS);
    Public long Getdelay (timeunit unit) {return Unit.convert (Trigger-system.nanotime (), nanoseconds);
      public int compareTo (delayed arg) {delayedtask that = (delayedtask) arg;
      if (Trigger < That.trigger) Return-1;
      if (Trigger > That.trigger) return 1;
    return 0;
    The public void Run () {//run All, want to does System.out.println (this);
    Public String toString () {return "[" + Delta + "s]" + "Task" + ID;
    }} public static void Main (string[] args) {Random rand = new Random ();
    Executorservice exec = Executors.newcachedthreadpool ();
    Delayedtasker tasker = new Delayedtasker ();
    for (int i = 0; i < i++) Tasker.addtask (New Delayedtask (Rand.nextint (5)));
    Exec.execute (Tasker);
  Exec.shutdown ();

 }
}

Results:

[0s] Task 1
[0s]task 2
[0s]task 3
[1s]task 6
[2s]task 5
[3s]task 8
[4s]task 0
[4s]task 4 [ 4s]task 7
[4s]task 9
finished Delayedtask

3. Java.util.concurrent.ScheduledThreadPoolExecutor
the class can schedule a task (thread) to run after a given delay, or perform a task periodically (repeatedly). You need to know the size of the thread pool in the constructor. The main methods are:

[1] Schedule
Public scheduledfuture<?> Schedule (Runnable command, long delay,timeunit unit)
Creates and executes a one-time operation that is enabled after a given delay.
Designated by:
-the schedule in the interface Scheduledexecutorservice;
Parameters:
-command-the task to be performed;
-delay-time to delay execution from now on;
-unit-The time unit of the delay parameter;
Return:
-Scheduledfuture that represents the completion of a pending task, and its get () method returns NULL when it completes.

[2] Scheduleatfixedrate
Public scheduledfuture<?> Scheduleatfixedrate (
Runnable command,long initialdelay,long period,timeunit unit)
Creates and executes a periodic operation that was first enabled after a given initial delay, with a given period of time; that is, the execution begins after InitialDelay, then executes after Initialdelay+period, followed by InitialDelay + 2 * Period After execution, and so forth. If any execution of a task encounters an exception, subsequent execution is canceled. Otherwise, the task can only be terminated by executing the cancellation or termination method of the program. If any of the execution of this task takes longer than its cycle, subsequent execution will be deferred, but not executed at the same time.
Designated by:
-The scheduleatfixedrate in the interface Scheduledexecutorservice;
Parameters:
-command-the task to be performed;
-initialdelay-The delay time for the first execution;
-period-cycles between successive executions;
Time units for-unit-initialdelay and period parameters;
Return:
-Scheduledfuture that represents the completion of a pending task, and its get () method throws an exception after it is canceled.
4. Design a thread performer with time delay characteristics
Class Scheduletasked Associates a scheduledthreadpoolexcutor, you can specify the size of the thread pool. By using the schedule method to know the thread and the latency, the shutdown method closes the thread pool. The logic of a specific task (thread) has some flexibility (compared to the previous design, the previous design must define the thread logic beforehand, but it can be modified by inheriting or decorating the thread-specific logic design).
Scheduletasker.java

Package com.zj.timedtask;
Import Java.util.concurrent.ScheduledThreadPoolExecutor;

Import Java.util.concurrent.TimeUnit;
  public class Scheduletasker {private int corepoolsize = 10;

  Scheduledthreadpoolexecutor Scheduler;
  Public Scheduletasker () {scheduler = new Scheduledthreadpoolexecutor (corepoolsize);
    public scheduletasker (int quantity) {corepoolsize = quantity;
  Scheduler = new Scheduledthreadpoolexecutor (corepoolsize);
  public void Schedule (Runnable event, long delay) {Scheduler.schedule (event, delay, timeunit.seconds);
  public void shutdown () {scheduler.shutdown ();
    public static void Main (string[] args) {Scheduletasker tasker = new Scheduletasker ();
      Tasker.schedule (New Runnable () {public void run () {System.out.println ("[1s]task 1");
    }, 1);
      Tasker.schedule (New Runnable () {public void run () {System.out.println ("[2s]task 2");
    }, 2); Tasker.schedule (New RunNable () {public void run () {System.out.println ("[4s]task 3");
    }, 4);
      Tasker.schedule (New Runnable () {public void run () {System.out.println ("[10s]task 4");

    }, 10);
  Tasker.shutdown ();

 }
}

Results:

[1s] Task 1
[2s]task 2
[4s]task 3
[10s]task 4 public
  void Run () {
   try {
    TimeUnit.SECONDS.sleep (3)] C7/>system.out.println ("I ' m going.");
    Monitor.gotmessage ();
   } catch (Interruptedexception e) {
    e.printstacktrace ();}}}

Class Monitor implements Runnable {
  private volatile Boolean go = false;

  Public synchronized void Gotmessage () throws Interruptedexception {go
   = true;
   Notify ();
  }

  Public synchronized void watching () throws Interruptedexception {while
   (go = False) wait
    ();
   System.out.println ("He has gone.");
  }

  public void Run () {
   try {
    watching ();
   } catch (Interruptedexception e) {
    e.printstacktrace ();
   }
  }
}

public class Wait {public
  static void Main (string[] args) {
   monitor monitor = new monitor ();
   MyObject o = new MyObject (monitor);
   New Thread (O). Start ();
   New Thread (monitor). Start ();


Results:

I ' m going.
He has gone.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.