Under 2019-06-04 Java multi-threading learning diary day25

Singleton design pattern

  Ensure that the design mode: to ensure that only one object class in memory

How to ensure that only one object tears in memory

  Create a control class to play, not to create another class of this class of objects. private

  In this class of the present redefine a class object. Singleton s;

  Providing a common access method, public static Singleton getInstance () {return s}

 

1. starving this way development of formula

2. type lazy to write the interview this way

Hungry man style is space for time, lazy man is time for space

When multi-threaded access, a hungry man does not create more than one object type, and lazy man is likely to create multiple objects

public  class demo1_Singleton { 

    public  static  void main (String [] args) {
         // the Singleton the Singleton new new S1 = (); member variable is privatized and not directly
         // the Singleton S1 = Singleton.s;
         // the Singleton S2 = the Singleton. S;
         // System.out.println (== S1 S2); 
        
        the Singleton S1 = Singleton.getInstance (); 
        the Singleton S2 = Singleton.getInstance (); 
        
        System.out.println (S1 == S2); 

    } 

} 
/ * // starving formula 
class the Singleton {  
    // private constructor, other classes can not access the constructor of
    Private the Singleton () {} 
    // Create a class object 
     Private the Singleton new new static the Singleton S = (); 
     // common to provide external access methods 
     public static Singleton getInstance () {// Get instance 
         return S; 
     } 
} * / 

// lazy, single embodiment of loading mode delay 
class the Singleton {
     // private constructor, other classes can not access the constructor of the 
    private the Singleton () {}
     // Create a class object 
     private   static the Singleton = S new new the Singleton ();
      // provide external access to a common method of 
     public  static the Singleton the getInstance () { // Get example 
         IF (S == null ) { 
            S = new new Singleton();
        }
         return s;
     }
}
Case

 

Multithreading (Runtime class)

  * Runtime class is an example of class single

public class demo2_Runtime {

    public static void main(String[] args) throws IOException {
        Runtime r1=Runtime.getRuntime();
        //r1.exec("shutdown -s -t 300");
        r1.exec("shutdown -a");

    }

}
Case

 

Timer: Timer

year - the year minus 1900

month - the month between 0-11

date - one day between January 1-3

hrs - the number of hours between 0-23

min - minutes between 0-59

sec - seconds between 0-59

Import java.util.Date;
 Import the java.util.Timer;
 Import java.util.TimerTask; 

public  class demo3_Timer { 

    / ** 
     * @param args 
     * @throws InterruptedException 
      * / 
    public  static  void main (String [] args) throws InterruptedException { 
        the Timer T = new new the Timer ();
         // scheduled task at the specified time specified
         // first parameter, the task is scheduled, the second parameter is the time of execution, the third parameter is too long repeated execution 
        t.schedule ( new new MyTimerTask (), new new Date(119, 5, 5, 0, 30, 10),3000);    
        
        while(true) {
            Thread.sleep(1000);
            System.out.println(new Date());
        }
    }

}

class MyTimerTask extends TimerTask {

    @Override
    public void run() {
        System.out.println("要起床了");
    }
}
Case

 

Communication between two threads

  When a plurality of threads concurrently executed, CPU default random thread switching

  If we want them to have to perform regularly, you can use communication, for example, each thread execute a print

How communication

  If you want the thread to wait on the call to wait ()

  If you want to wake up waiting threads, call notify ()

  These two methods must then perform a synchronization code, and using the synchronization lock object to call

public class demo1_Notify {

    public static void main(String[] args) {
        printer p1=new printer();
        new Thread(){
            public void run(){
                while(true){
                    try {
                        p1.print1();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        new Thread(){
            public void run(){
                while(true){
                    try {
                        p1.print2();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }.start();

    }

}
class printer{
    private int flag =1;
    public void print1() throws InterruptedException{
        synchronized (this){
            if (flag !=1) {
                this.wait();  //当前线程等待
            }
        System.out.print("明");
        System.out.print("天");
        System.out.print("是");
        System.out.print("好");
        System.out.print("日");
        System.out.print("子");
        System.out.print("\ R & lt \ n-" ););
        In Flag = 2 ;
         the this .notify (); // random wake-up threads waiting individual 
        
    } 
}     
    public  void print2 () throws InterruptedException {
          the synchronized ( the this ) {
              IF (In Flag = 2! {)
                 the this .wait (); 
            } 
        the System. Out.print ( "now" ); 
        of System.out.print ( "days" ); 
        of System.out.print ( "days" ); 
        of System.out.print ( "gas" 
        of System.out.print ( "true");
        System.out.print("好");
        System.out.print("\r\n");
        flag =1;
        this.notify();
    }
 }
}
Case

 

Three or more communication threads between the three

 * Multiple threads of communication problems

  Random wake up one thread * notify () method

  * Wake up all threads notifyAll () method

  * JDK5 can not wake up before a specified thread

  * If the communication between a plurality of threads requires use notifyAll () notifies all threads, while repeatedly using the determination condition

 

jdk1.5 new features mutex

Synchronize

  Use lock ReentrantLock class () and unlock () method to synchronize

communication

  Use newCondition ReentrantLock class () method gets the object Condition

  Condition time to wait to use the await () method, the wake-up time with the signal () method

  Different threads use Condition, so you can distinguish which threads wake-up time to find

  

Guess you like

Origin www.cnblogs.com/JungTan0113/p/10973995.html
Recommended