1、 Multithreading ( Singleton design pattern )

  • Singleton design pattern : Make sure the class has only one object in memory .

  • How to ensure that a class has only one object in memory ?

    • (1) Control class creation , Don't let other classes create objects of this class .private
    • (2) Define an object of this class in this class .Singleton s;
    • (3) Provide public access . public static Singleton getInstance(){return s}
  • There are two ways to write a single example :

    • (1) Hungry Chinese style Development in this way .
    • // Hungry Chinese style 
      class Singleton {
      //1, Private constructor
      private Singleton(){}
      //2, Create objects of this class
      private static Singleton s = new Singleton();
      //3, Provide public access to the outside world
      public static Singleton getInstance() {
      return s;
      } public static void print() {
      System.out.println("11111111111");
      }
      }
    • (2) Slacker type Interview writing this way . Multithreading problem ?
    • // Slacker type , Delayed loading mode of single example 
      class Singleton {
      //1, Private constructor
      private Singleton(){}
      //2, Declare a reference to this class
      private static Singleton s;
      //3, Provide public access to the outside world
      public static Singleton getInstance() {
      if(s == null)
      // Threads 1, Threads 2
      s = new Singleton();
      return s;
      } public static void print() {
      System.out.println("11111111111");
      }
      }
    • (3) Third format
    • class Singleton {
      private Singleton() {} public static final Singleton s = new Singleton();//final Is the ultimate meaning , By final The decorated variable cannot be changed
      }

2、 Multithreading (Runtime class )

  • Runtime Class is a singleton class

    • Runtime r = Runtime.getRuntime();
      //r.exec("shutdown -s -t 300"); //300 Shut down in seconds
      r.exec("shutdown -a"); // Cancel shutdown

3、 Multithreading (Timer)

  • Timer class : timer

     public class Demo5_Timer {
    /**
    * @param args
    * timer
    * @throws InterruptedException
    */
    public static void main(String[] args) throws InterruptedException {
    Timer t = new Timer();
    t.schedule(new MyTimerTask(), new Date(114,9,15,10,54,20),3000); while(true) {
    System.out.println(new Date());
    Thread.sleep(1000);
    }
    }
    }
    class MyTimerTask extends TimerTask {
    @Override
    public void run() {
    System.out.println(" Get up and recite English words ");
    } }

4、 Multithreading ( Communication between two threads )

  • 1. When communication is needed

    • When multiple threads execute concurrently , By default CPU It's random thread switching
    • If we want them to do it regularly , You can use communication , For example, one print per thread
  • 2. How to communicate
    • If you want the thread to wait , Just call wait()
    • If you want to wake up the waiting thread , Just call notify();
    • These two methods must be executed in the synchronization code , And use the synchronization lock object to call

5、 Multithreading ( Three or more threads communicate )

  • The problem of multiple threads communicating

    • notify() The method is to wake up a thread at random
    • notifyAll() The way is to wake up all threads
    • JDK5 Unable to wake up a specified thread before
    • If multiple threads communicate with each other , Need to use notifyAll() Notify all threads , use while To judge the condition repeatedly

6、 Multithreading (JDK1.5 New features of mutex )

  • 1. Sync

    • Use ReentrantLock Class lock() and unlock() Method to synchronize
  • 2. signal communication
    • Use ReentrantLock Class newCondition() Method can obtain Condition object
    • Use when you need to wait Condition Of await() Method , When waking up signal() Method
    • Different threads use different Condition, In this way, we can distinguish which thread to look for when waking up

7、 Multithreading ( Thread group overview and use )

  • A: Thread group Overview

    • Java Use in ThreadGroup To represent thread groups , It can classify and manage a batch of threads ,Java Allows the program to control the thread group directly .
    • By default , All threads belong to the main thread group .
      • public final ThreadGroup getThreadGroup()// Get the group he belongs to through the thread object
      • public final String getName()// Get the name of his group through the thread group object
    • We can also set up groups for threads
      • 1,ThreadGroup(String name) Create a thread group object and assign it a name
      • 2, Creating thread objects
      • 3,Thread(ThreadGroup?group, Runnable?target, String?name)
      • 4, Set the priority of the whole group or the daemons
    • B: Case presentation
      • Use of thread groups , The default is the main thread group
  • MyRunnable mr = new MyRunnable();
    Thread t1 = new Thread(mr, " Zhang San ");
    Thread t2 = new Thread(mr, " Li Si ");
    // Get thread groups
    // Methods in thread class :public final ThreadGroup getThreadGroup()
    ThreadGroup tg1 = t1.getThreadGroup();
    ThreadGroup tg2 = t2.getThreadGroup();
    // Methods in thread group :public final String getName()
    String name1 = tg1.getName();
    String name2 = tg2.getName();
    System.out.println(name1);
    System.out.println(name2);
    // Through the result we know : Threads by default belong to main Thread group
    // Pass the following test , You should be able to see , In silence , All threads belong to the same group
    System.out.println(Thread.currentThread().getThreadGroup().getName());
    • Set your own thread group
  • // ThreadGroup(String name)
    ThreadGroup tg = new ThreadGroup(" This is a new group "); MyRunnable mr = new MyRunnable();
    // Thread(ThreadGroup group, Runnable target, String name)
    Thread t1 = new Thread(tg, mr, " Zhang San ");
    Thread t2 = new Thread(tg, mr, " Li Si "); System.out.println(t1.getThreadGroup().getName());
    System.out.println(t2.getThreadGroup().getName()); // Set background thread by group name , Indicates that all threads in this group are background threads
    tg.setDaemon(true);

8、 Multithreading ( Five states of thread )

  • Look at the picture
  • newly build , be ready , function , Blocking , Death

9、 Multithreading ( Overview and use of thread pool )

  • A: Thread pool overview

    • The cost of starting a new thread is relatively high , Because it involves interacting with the operating system . And using thread pool can improve the performance very well , Especially when a large number of threads with short lifetime are to be created in the program , More should consider using thread pool . After the completion of each thread code in the thread pool , It's not going to die , Instead, go back to the thread pool and become idle again , Wait for the next object to use . stay JDK5 Before , We have to implement our own thread pool manually , from JDK5 Start ,Java Built in thread pool support
  • B: An overview of the use of the built-in thread pool
    • JDK5 I added a new one Executors Factory class to generate thread pool , There are several ways

      • public static ExecutorService newFixedThreadPool(int nThreads)
      • public static ExecutorService newSingleThreadExecutor()
      • The return values of these methods are ExecutorService object , This object represents a thread pool , It can be executed Runnable Object or Callable Object represents the thread . It provides the following methods
      • Future<?> submit(Runnable task)
      • Future submit(Callable task)
    • Use steps :
      • Create thread pool object
      • establish Runnable example
      • Submit Runnable example
      • Close thread pool
    • C: Case presentation
      • Is submitted Runnable
  • // public static ExecutorService newFixedThreadPool(int nThreads)
    ExecutorService pool = Executors.newFixedThreadPool(2); // It can be executed Runnable Object or Callable Object represents the thread
    pool.submit(new MyRunnable());
    pool.submit(new MyRunnable()); // End thread pool
    pool.shutdown();

10、 Multithreading ( How to implement multithreaded programs 3)

  • Is submitted Callable

  • // Create thread pool object 
    ExecutorService pool = Executors.newFixedThreadPool(2); // It can be executed Runnable Object or Callable Object represents the thread
    Future<Integer> f1 = pool.submit(new MyCallable(100));
    Future<Integer> f2 = pool.submit(new MyCallable(200)); // V get()
    Integer i1 = f1.get();
    Integer i2 = f2.get(); System.out.println(i1);
    System.out.println(i2); // end
    pool.shutdown(); public class MyCallable implements Callable<Integer> { private int number; public MyCallable(int number) {
    this.number = number;
    } @Override
    public Integer call() throws Exception {
    int sum = 0;
    for (int x = 1; x <= number; x++) {
    sum += x;
    }
    return sum;
    } }
  • How to implement multithreaded programs 3 Advantages and disadvantages of

    • benefits :

      • You can have a return value
      • You can throw an exception
    • disadvantages :

      • The code is more complex , So it's not used in general

11、 Design patterns ( Overview and use of simple factory model )

  • A: Overview of the simple factory model

    • Also called static factory method mode , It defines a specific factory class that is responsible for creating instances of some classes
  • B: advantage
    • The client does not need to be responsible for the creation of objects , Thus, the responsibilities of various categories are clarified
  • C: shortcoming
    • This static factory class is responsible for the creation of all objects , If there are new objects added , Or some objects are created differently , We need to constantly modify the factory class , Not conducive to later maintenance
  • D: Case presentation
    • Animal abstract class :public abstract Animal { public abstract void eat(); }
    • Specific dogs :public class Dog extends Animal {}
    • Specific cats :public class Cat extends Animal {}
    • Start , Create your own objects for each specific content in the test class , however , If the work of creating objects is troublesome , We need someone to do it , So you know a special class to create objects .
  • public class AnimalFactory {
    private AnimalFactory(){} //public static Dog createDog() {return new Dog();}
    //public static Cat createCat() {return new Cat();} // improvement
    public static Animal createAnimal(String animalName) {
    if(“dog”.equals(animalName)) {}
    else if(“cat”.equals(animale)) { }else {
    return null;
    }
    }
    }

12、 Design patterns ( Overview and use of factory method patterns )

  • A: Overview of the factory approach pattern

    • In the factory method pattern, the abstract factory class is responsible for defining the interface for creating objects , The creation of concrete objects is implemented by concrete classes that inherit Abstract factories .
  • B: advantage
    • The client does not need to be responsible for the creation of objects , Thus, the responsibilities of various categories are clarified , If there are new objects added , Just add a specific class and a specific factory class , Does not affect existing code , Later maintenance is easy , Enhance the expansibility of the system
  • C: shortcoming
    • Need to write extra code , Increased workload
  • D: Case presentation
  •  Animal abstract class :public abstract Animal { public abstract void eat(); }
    Factory interface :public interface Factory {public abstract Animal createAnimal();}
    Specific dogs :public class Dog extends Animal {}
    Specific cats :public class Cat extends Animal {}
    Start , Create your own objects for each specific content in the test class , however , If the work of creating objects is troublesome , We need someone to do it , So you know a special class to create objects . It's too much trouble to change the code every time , Improve... With factory methods , Provide a specific factory for each specific implementation .
    Dog factory :public class DogFactory implements Factory {
    public Animal createAnimal() {…}
    }
    Cat factory :public class CatFactory implements Factory {
    public Animal createAnimal() {…}
    }

13、GUI( How to create a window and display )

  • Graphical User Interface( Graphical user interface ).
  • Frame f = new Frame(“my window”);
    f.setLayout(new FlowLayout());// Set up the layout manager
    f.setSize(500,400);// Set the window size
    f.setLocation(300,200);// Set where the form will appear on the screen
    f.setIconImage(Toolkit.getDefaultToolkit().createImage("qq.png"));
    f.setVisible(true);

14、GUI( Layout manager )

  • FlowLayout( Streaming layout manager )

    • From left to right .
    • Panel The default layout manager .
  • BorderLayout( Border layout manager )
    • In the east , south , In the west , north , in
    • Frame The default layout manager .
  • GridLayout( Grid layout manager )
    • Regular matrix
  • CardLayout( Card layout manager )
    • tab
  • GridBagLayout( Grid package layout manager )
    • Irregular matrix

15、GUI( Form listening )

Frame f = new Frame(" My window ");
// The event source is the form , Register the listener to the event source
// The event object is passed to the listener
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
// Exit virtual machine , close window
System.exit(0);
}
});

16、GUI( Mouse monitor )

17、GUI( Keyboard listening and keyboard events )

18、GUI( Action monitoring )

19、 Design patterns ( adapter design pattern )

  • a. What is an adapter

    • When using the monitor , You need to define an event listener interface .
    • Usually there are multiple methods in an interface , And not everything in the program has to use , But it has to be rewritten , It's complicated .
    • Adapters simplify these operations , When we define a listener, we just inherit the adapter , Then rewrite the required method .
  • b. Adapter principle
    • An adapter is a class , Implemented the listener interface , All abstract methods are rewritten , But the methods are all empty .
    • Adapter classes need to be defined as abstract , Because creating this kind of object , It doesn't make sense to call an empty method
    • The purpose is to simplify the operation of programmers , Inherit adapter when defining listener , Just rewrite the methods you need .

20、GUI( Need to know )

  • Event handling

    • event : An operation of the user
    • Event source : Components operated
    • Monitor : An object of a custom class , Implemented the listener interface , Contains event handling methods , Add a listener to the event source , When the event occurs, the virtual machine will automatically call the event processing method in the listener

JavaEE Basics ( twenty-five )/ Multithreading 、GUI More articles about

  1. Bootstrap &lt; Foundation 25 &gt; Warning (Alerts)

    Warning (Alerts) as well as Bootstrap Provided for warning class. Warning (Alerts) Provides users with a way to define message styles . They provide context feedback for typical user operations . You can add a ...

  2. JavaEE Basics ( 15、 ... and )/ aggregate

    1. Collections framework ( Object array overview and use ) A: Case presentation demand : I have a 5 A student , Please take this 5 Students' information is stored in an array , And traverse the array , Get every student information . Student[] arr = new Student ...

  3. Tamp Java Basics ( twenty-five )——JDBC The use of,

    1.JDBC Introduce JDBC The full name is Java Data Base Connectivity(Java Database connection ). It's one for execution SQL Of the statement Java API, It can provide unified access for a variety of relational databases ( for example MyS ...

  4. Bootstrap &lt; Foundation 29 &gt; panel (Panels)

    Bootstrap panel (Panels). The panel assembly is used to put DOM Insert the component into a box . Create a basic panel , Only need to <div> Element to add class .panel  and class .pa ...

  5. Bootstrap &lt; Foundation 28 &gt; List group

    List group . List components are used to present complex and custom content in the form of lists . The steps to create a basic list group are as follows : To the element <ul> add to class .list-group. towards <li> add to cl ...

  6. Bootstrap &lt; Foundation 26 &gt; Progress bar

    Bootstrap Progress bar . In this tutorial , You will see how to use Bootstrap Create load . Redirection or action status progress bar . Bootstrap The progress bar uses CSS3 Transition and animation to get the effect .Internet ...

  7. Bootstrap&lt; Foundation 24 &gt; thumbnail

    Bootstrap thumbnail . Most sites need to lay out images in the grid . video . Text etc. .Bootstrap Thumbnails provide an easy way to do this . Use Bootstrap The steps to create a thumbnail are as follows : Add around the image with ...

  8. Bootstrap &lt; Foundation 22 &gt; Large screen (Jumbotron)

    Bootstrap Another feature supported , Large screen (Jumbotron). As the name suggests, this component can increase the size of the title , And add more margins to the landing page (margin). Use the big screen (Jumbotron) The steps are as follows : ...

  9. Bootstrap&lt; Foundation 20 &gt; label

    Bootstrap label . Tags can be used to count . Tips or other tags on the page display . Use class .label  To display labels , As the following example shows : <!DOCTYPE html> <html> ...

  10. JAVA Looking back ( twenty-five )——Lock Use of locks 、 The deadlock problem 、 Multithreaded producers and consumers 、 Thread pool 、 Anonymous inner classes use multithreading 、 Timer 、 Interview questions

    JAVA Looking back ( twenty-five )--Lock Use of locks . The deadlock problem . Multithreaded producers and consumers . Thread pool . Anonymous inner classes use multithreading . Timer . Interview questions Copyright notice : Reprint must indicate that this article is from the program ape Du Pengcheng's blog :http://blog ...

Random recommendation

  1. sql Query in when...then sentence

    ),jbrq, ),'/','-')as jbrq, ' then ' Enable ' when ' then ' not enabled ' else ' modify ' end cbzt,shzt from jc_yscbfxb sel ...

  2. Android And AlarmManager( Global timer / alarm clock ) Specify the length of time or perform an operation as a cycle

    1.AlarmManager, seeing the name of a thing one thinks of its function , Namely “ remind ”, yes Android A system level prompt service commonly used in , Can be achieved from a specified time , Perform an operation at a fixed interval , So often with the radio (Broadcast) Continuous use ...

  3. Java in final、finally and finalize The difference between ( turn )

    http://www.cnblogs.com/bluestorm/archive/2012/04/22/2464746.html final  Used to declare properties , Methods and classes , Respectively indicates that the property is immutable , Method cannot be overridden , ...

  4. Sumdiv( All kinds of math )

    http://poj.org/problem?id=1845 The question : seek A^B The sum of all divisors of 9901 modulus : After doing this, I learned N A lot of math : One : Any integer can be uniquely decomposed into the product of prime factors :A = p1^ ...

  5. be based on FPGA It's a signal jitter cancellation

    The last one wrote a key to eliminate shaking , A counter is needed for key jitter elimination . But some signals don't need to be so responsible , It's just shaking . So I made a little modification on the basis of my last blog , So there's this signal jitter elimination program module sig_nojitte ...

  6. 【 Reading notes 】iOS-“ a ” Use multithreading to improve performance

    iPhone Will have support for different types of multithreading API The ability of , these API Include :POSIX Threads ,NSObject,NSThread and NSOperation. iPhone The operating system is a real preemptive , Multitask operating system , ...

  7. CSS List instances

    CSS The list property allows you to place . Change list item flag , Or use the image as a list item flag .CSS A list of attributes (list) attribute describe list-style Abbreviated attribute . Used to set all the properties used for the list in one declaration .list-styl ...

  8. dotnet core Download address as well as sdk and runtime Of version Briefly explain

    1. dotnet core 2.1 Download address https://dotnet.microsoft.com/download/dotnet-core/2.1 2. dotnet core 2.2 Next to ...

  9. Teach you to calculate easily AOE Network critical path

    know AOE network In the directed graph , Use vertices to represent activities , Use the directed edge to indicate the order in which activities begin , We call this directed graph AOV The Internet :AOV The network can reflect the sequence of tasks ( A topological sort ). stay AOV Adding weights to the edges of the net indicates the amount of time needed to complete the activity ...

  10. Solve the problem that the application cannot start normally 0xc0150002 Other questions

    1. When the program runs wrong , Right click “ My computer ”, And then click “ management ”→“ Event viewer ”→“Windows journal ”→“ Applications ”, Check error messages : 1> “E:\IPCam_share\ARP\ Data processing \Hg ...