javaSE learning day 25
java knowledge
Multithreading (single design mode)
-
Singleton design pattern: ensure that the class has only one object in memory.
-
How to ensure that a class has only one object in memory?
- (1) Control the creation of classes. Do not 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) This is the way to develop in the Han Dynasty.
-
//Hungry man class Singleton { //1. Private constructor. Other classes cannot access the constructor private Singleton(){} //2. Create this type of object private static Singleton s = new Singleton(); //3. Provide public access methods public static Singleton getInstance() { //Get examples return s; } public static void print() { System.out.println("11111111111"); } }
- (2) Lazy interview writing this way (single example of delayed loading mode). Multithreading problem? It is possible to create multiple objects
-
//Lazy, single case delayed loading mode class Singleton { //1. Private construction method private Singleton(){} //2. Declare a reference of this class private static Singleton s; //3. Provide public access methods public static Singleton getInstance() { if(s == null) //Thread 1, thread 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 means final. Variables modified by final cannot be changed }
-
The difference between the hungry and the lazy
-
1. The hungry type is space for time, the lazy type is time for space
-
2. In multithreaded access, the hungry type will not create multiple objects, while the lazy type may create multiple objects
Multithreading (Runtime class)
- Runtime class is a singleton class
-
Runtime r = Runtime.getRuntime(); //r.exec("shutdown -s -t 300"); / / shutdown in 300 seconds r.exec("shutdown -a"); //shutdown -a
-
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(); //Schedule a task at a specified time //The first parameter is the scheduled task, the second parameter is the execution time, and the third parameter is the repeated execution after a long time 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 memorize English words"); } }
Multithreading (communication between two threads)
- 1. When to communicate
- When multiple threads execute concurrently, the CPU switches threads randomly by default
- If we want them to execute regularly, we can use communication, such as printing once per thread
- 2. How to communicate
- Call wait() if you want the thread to wait
- If you want to wake up the waiting thread, call notify();
- These two methods must be executed in the synchronization code and called using the synchronization lock object
Multithreading (three or more threads communicating)
- The problem of multi thread communication
- The notify() method wakes up a thread at random
- The notifyAll() method wakes up all threads
- Unable to wake up a specified thread before JDK5
- If multiple threads communicate with each other, you need to use notifyAll() to notify all threads and while to repeatedly judge the conditions
- Be careful
- 1. In the synchronization code block, the wait method is called by the object lock
- 2. Why are wait and notify methods defined in the Object class?
- Because the lock Object can be any Object and the Object is the base class of all classes, the wait method and notify method need to be defined in the Object class
- 3. What is the difference between sleep method and wait method?
- a. The sleep method must pass in parameters, which are time. When the time is up, it will wake up automatically
- The wait method can pass in parameters or not. The passed in parameters are waiting after the parameter's time ends. The passed in parameters are waiting directly
- b. sleep method in the synchronization function or synchronization code block, does not release the lock, and sleeps with the lock when sleeping
- The wait method releases the lock in the synchronization function or synchronization code block
- a. The sleep method must pass in parameters, which are time. When the time is up, it will wake up automatically
Multithreading (a new feature of JDK 1.5, mutex)
- 1. synchronization
- Use the lock() and unlock() methods of the ReentrantLock class to synchronize
- 2. communication
- Use the newCondition() method of the ReentrantLock class to get the Condition object
- Use the await() method of Condition when waiting, and the signal() method when waking up
- Different threads use different conditions, so that you can distinguish which thread to look for when waking up
Multithreading (overview and use of thread groups)
-
A: Thread groups overview
- In Java, ThreadGroup is used to represent thread group. It can manage a batch of threads by category. Java allows programs to control thread group directly.
- By default, all threads belong to the main thread group.
- public final ThreadGroup getThreadGroup() / / get the group to which he belongs through the thread object
- public final String getName() / / get the name of another group through the thread group object
- We can also group threads
- 1. ThreadGroup (string name) creates a thread group object and assigns a name to it
- 2. Create thread object
- 3,Thread(ThreadGroup?group, Runnable?target, String?name)
- 4. Set the priority or daemons of the whole group
- B: Case demonstration
- Use of thread group, the default is the main thread group
-
MyRunnable mr = new MyRunnable(); //Create a subclass object of Runnable Thread t1 = new Thread(mr, "Zhang San"); //Put thread t1 in the group Thread t2 = new Thread(mr, "Li Si"); //Put thread t2 in the group //Get thread group // 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 results, we know that threads belong to the main thread group by default // Through the following tests, you should be able to see that by default, all threads belong to the same group System.out.println(Thread.currentThread().getThreadGroup().getName());
- Set thread group by yourself
-
// 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()); //Setting background threads by group name means that all threads in the group are background threads tg.setDaemon(true);
Multithreading (five states of threads)
- New, ready, running, blocking, dead
Multithreading (overview and use of thread pool)
- A: Thread pool overview
- Starting a new thread is expensive because it involves interacting with the operating system. The use of thread pool can improve performance, especially when a large number of short-lived threads are to be created in the program, the use of thread pool should be considered. After each thread code in the thread pool ends, it will not die. Instead, it will return to the thread pool again and become idle, waiting for the next object to use. Before JDK5, we must manually implement our own thread pool. Starting from JDK5, Java has built-in support for thread pool
- B: An overview of the use of the built-in thread pool
- JDK5 has added an Executors factory class to generate thread pools. There are several methods as follows
- public static ExecutorService newFixedThreadPool(int nThreads)
- public static ExecutorService newSingleThreadExecutor()
- The return value of these methods is ExecutorService object, which represents a thread pool and can execute the thread represented by Runnable object or Callable object. It provides the following methods
- Future<?> submit(Runnable task)
- Future submit(Callable task)
- Use steps:
- Create thread pool object
- Create Runnable instance
- Submit Runnable instance
- Close thread pool
- C: Case demonstration
- Submitted by Runnable
- JDK5 has added an Executors factory class to generate thread pools. There are several methods as follows
-
// public static ExecutorService newFixedThreadPool(int nThreads) ExecutorService pool = Executors.newFixedThreadPool(2); //Create thread pool // Can execute the thread represented by Runnable object or Callable object pool.submit(new MyRunnable()); //Put thread into pool and execute pool.submit(new MyRunnable()); //End thread pool pool.shutdown();
Multithreading (mode 3 of multithreading program implementation)
-
Callable submitted
-
// Create thread pool object ExecutorService pool = Executors.newFixedThreadPool(2); // Can execute the thread represented by Runnable object or Callable object 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; } }
-
Advantages and disadvantages of multithreaded program implementation mode 3
-
Benefits:
- Can have return value
- Exception can be thrown
-
Disadvantages:
- The code is complex, so it is not used generally
-
Design patterns (overview and use of simple factory patterns)
- A: Simple factory model overview
- Also known as static factory method pattern, it defines a specific factory class that is responsible for creating instances of some classes
- B: advantages
- The client does not need to be responsible for the creation of objects, thus clarifying the responsibilities of each class
- C: drawback
- This static factory class is responsible for the creation of all objects. If new objects are added or some objects are created in different ways, the factory class needs to be constantly modified, which is not conducive to later maintenance
- D: Case demonstration
- Animal abstract class: public abstract animal {public abstract void eat();}
- Specific dog: public class Dog extends Animal {}
- Specific cat: public class Cat extends Animal {}
- At first, each specific content in the test class creates its own object. However, if the work of creating an object is troublesome, someone needs to do it specially, so we know a special class to create an object.
-
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; } } }
Design patterns (overview and use of factory method patterns)
- A: Overview of the factory approach model
- In the factory method pattern, the abstract factory class is responsible for defining the interface for creating objects, and the creation of concrete objects is implemented by the concrete class that inherits the abstract factory.
- B: advantages
- The client does not need to be responsible for the creation of objects, so as to clarify the responsibilities of each class. If there are new objects to be added, only a specific class and a specific factory class need to be added, which will not affect the existing code. Later maintenance is easy, and the expansibility of the system is enhanced
- C: drawback
- Additional code is needed to increase the workload
- D: Case demonstration
-
Animal abstract class: public abstract animal {public abstract void eat();} Factory interface: public interface factory {public abstract animal createinitial();} Specific dog: public class Dog extends Animal {} Specific cat: public class Cat extends Animal {} At first, each specific content in the test class creates its own object. However, if the work of creating an object is troublesome, someone needs to do it specially, so we know a special class to create an object. It is found that it is too troublesome to modify the code every time. We use the factory method to improve and 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() {...} }
GUI (how to create a window and display it)
- Graphical user interface.
-
Frame f = new Frame("my window"); f.setLayout(new FlowLayout());//Set up layout manager f.setSize(500,400);//Set form size f.setLocation(300,200);//Set where the form appears on the screen f.setIconImage(Toolkit.getDefaultToolkit().createImage("qq.png")); Button b1 = new Butten("Button 1"); f.add(b1); f.setLayout(new FlowLayout()); f.setVisible(true); //Set form visible
GUI (layout manager)
- FlowLayout (flow layout manager)
- From left to right.
- Panel default layout manager.
- BorderLayout (border layout manager)
- East, South, West, north, middle
- Frame the default layout manager.
- GridLayout (grid layout manager)
- Regular matrix
- CardLayout (card layout manager)
- tab
- GridBagLayout (grid package layout manager)
- Irregular matrix
GUI (form listening)
Frame f = new Frame("My form"); //Event source is form, register listener to event source //Event object passed to listener f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //Exit virtual machine, close window System.exit(0); } });
GUI (mouse monitor)
- slightly
GUI (keyboard listening and keyboard events)
- slightly
GUI (action monitoring)
- slightly
Design mode (adapter design mode)
- a. What is an adapter
- When using a listener, you need to define an event listener interface
- Usually there are many methods in the interface, and not all of them are used in the program, but they have to be rewritten, which is very tedious
- The adapter simplifies these operations. When we define a listener, we only need to inherit the adapter and rewrite the required methods
- b. Adapter principle
- The adapter is a class that implements the listener interface. All abstract methods are rewritten, but the methods are all empty
- The adapter class needs to be defined as abstract, because it is meaningless to call an empty method when creating the class object
- The purpose is to simplify the operation of the programmer. When defining the listener, inherit the adapter and only rewrite the required methods
GUI (need to know)
- event processing
- Event: an action of the user
- Event source: components operated on
- Listener: an object of a user-defined class, which implements the listener interface, including event handling methods. The listener is added to the event source. When an event occurs, the virtual machine will automatically call the event handling methods in the listener
Other knowledge
nothing