2019-06-04 Java Learning Diary under day25 Multithread

Singleton Design Patterns

Guarantee Design Patterns: Guarantee that the class has only one object in memory

How to ensure that tears have only one object in memory

Controlling the creation of class hits does not allow other classes to create objects of this class. private

Redefining an object of this class in this class. Singleton s;

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

 

1. Hungry Chinese style development in this way

2. Lazy Interview Writing in this Way

Hungry Chinese style is space for time, lazy Chinese style is time for space.

In multithreaded access, hungry Chinese may not create multiple objects, while lazy Chinese may create multiple objects.

public class demo1_Singleton {

    public static void main(String[] args) {
        //Singleton s1=new Singleton();  Membership variables are privatized and cannot be called directly
        //Singleton s1=Singleton.s;
        //Singleton s2=Singleton.s;
        //System.out.println(s1 ==s2);
        
        Singleton s1=Singleton.getInstance();
        Singleton s2=Singleton.getInstance();
        
        System.out.println(s1 == s2);

    }

}
/*//Hungry man
class Singleton{
    //Private constructor, which cannot be accessed by other classes
    private Singleton(){}
    //create a class object
     private  static Singleton s= new Singleton();
     //Providing public access to the outside world
     public static Singleton getInstance(){ //Get examples
         return s;
     }
}*/

//Slacker type,Delayed Loading Mode for Singletons
class Singleton{
    //Private constructor, which cannot be accessed by other classes
    private Singleton(){}
    //create a class object
     private  static Singleton s= new Singleton();
     //Providing public access to the outside world
     public static Singleton getInstance(){ //Get examples
         if (s==null) {
            s =new Singleton();
        }
         return s;
     }
}
case

 

Multithreading (Runtime class)

* The Runtime class is a singleton class

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 - year minus 1900

Month - 0 - November

date - someday between 1 and 3 in mid-January

Hours between hrs - 0-23

Minutes between min - 0-59

sec - 0-59 seconds

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class demo3_Timer {

    /**
     * @param args
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException {
        Timer t = new Timer();
        //Schedule assigned tasks at specified times
        //First parameter,It's an assigned task.,The second parameter is the execution time.,The third parameter is how long it takes to repeat execution.
        t.schedule(new MyTimerTask(), 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("We need to get up.");
    }
}
case

 

Communication between two threads

When multiple threads are executed concurrently, by default the CPU switches threads randomly

If we want them to execute regularly, we can use communication, such as printing once per thread.

How to communicate

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

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

These two methods must be executed in resynchronized code and invoked using synchronous lock objects

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();  //Current thread waiting
            }
        System.out.print("bright");
        System.out.print("day");
        System.out.print("yes");
        System.out.print("good");
        System.out.print("day");
        System.out.print("son");
        System.out.print("\r\n");
        flag=2;
        this.notify();//Random wake-up of a single waiting thread
        
    }
}    
    public void print2() throws InterruptedException{
         synchronized (this){
             if (flag != 2) {
                this.wait();
            }
        System.out.print("this");
        System.out.print("day");
        System.out.print("day");
        System.out.print("gas");
        System.out.print("really");
        System.out.print("good");
        System.out.print("\r\n");
        flag =1;
        this.notify();
    }
 }
}
case

 

Thread communication between three or more threads

* The problem of multi-threaded communication

* random wake-up of a thread when notify () method

* wake up all threads when notifyAll () method

* JDK5 could not wake up a specified thread before

* If multiple threads communicate with each other, notify all () is used to notify all threads and while is used to judge the condition repeatedly.

 

New feature mutex of jdk1.5

synchronization

Synchronization using the lock () and unlock () methods of the ReentrantLock class

Signal communication

Use the new Condition () method of the ReentrantLock class to get the Condition object

Use Condition's await () method when you need to wait, and signal () method when you wake up.

Different threads use different conditions so that they can distinguish which thread to look for when waking up

Keywords: PHP Java

Added by Moneypenny on Tue, 04 Jun 2019 20:48:12 +0300