Java EE Basics (25)/multithreading, GUI

Source: Internet
Author: User
Tags event listener

1, multi-threaded (single case design mode)
  • Singleton design Pattern: guarantees that the class has only one object in memory.

  • How do you ensure that the class has only one object in memory?

    • (1) control the creation of classes, and do not allow other classes to create objects of this class. Private
    • (2) Define an object of this class in this class. Singleton s;
    • (3) to provide public access. public static Singleton getinstance () {return s}
  • Single-instance syntax:

    • (1) A Hungry man development in this way.
    •  ///A Hungry man class Singleton {//1, private constructor-Singleton () {}//2, creating this class object private static Singl    Eton s = new Singleton ();    3, provide public access method publicly static Singleton getinstance () {return s;    } public static void print () {System.out.println ("11111111111"); }}  
    • (2) A lazy-face interview is written in this way. Multi-threaded problem?
    •  //lazy, single-instance lazy-load mode class Singleton {//1, Private-constructor-Singleton () {}//2, declaring a reference to this class private    static Singleton s; 3, provide public access method publicly static Singleton getinstance () {if (s = = null)//thread 1, thread 2 s = new Si        Ngleton ();    return s;    } public static void print () {System.out.println ("11111111111"); }}  
    • (3) Third format
    •   class Singleton {private Singleton () {} public static fin Al Singleton s = new Singleton ();//final is the final meaning, the final modified variable cannot be changed}  
2. Multithreading (Runtime Class)
    • The runtime class is a singleton class
      • Runtime r = Runtime.getRuntime();//r.exec("shutdown -s -t 300");     //300秒后关机r.exec("shutdown -a");              //取消关机
3. Multithreading (Timer)
    • Timer class: Timer

          public class Demo5_Timer {        /**         * @param args         * 计时器         * @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("起床背英语单词");        }    }
4. Multithreading (communication between two threads)
    • 1. When to communicate
      • When multiple threads are executing concurrently, the CPU is randomly switching threads by default
      • If we want them to execute regularly, we can use communication, for example, each thread performs a print
    • 2. How to Communicate
      • Call Wait () if you want the thread to wait
      • If you want to wake up the waiting thread, call notify ();
      • Both methods must be executed in the synchronization code, and the synchronization lock object is used to invoke the
5, multi-threaded (three or more than three threads communication)
    • Issues with multiple thread communication
      • The Notify () method is a random wake-up of a thread
      • The Notifyall () method is to wake all threads
      • JDK5 Unable to wake a specified thread before
      • If the communication between multiple threads, you need to use Notifyall () to notify all threads, use while to repeatedly judge the condition
6, Multi-threaded (JDK1.5 new feature mutex)
    • 1. Synchronization
      • Synchronizing using the Lock () and Unlock () Methods of the Reentrantlock class
    • 2. Communication
      • Use the Newcondition () method of the Reentrantlock class to get the condition object
      • Use condition's await () method when you need to wait, wake up with the signal () method
      • Different threads use different condition so that you can tell which thread to look for when waking up.
7. Multithreading (Overview and use of thread groups)
  • A: Thread Group Overview
    • Java uses threadgroup to represent thread groups, which can classify a batch of threads, and Java allows programs to control thread groups directly.
    • By default, all threads belong to the main thread group.
      • Public Final Threadgroup Getthreadgroup ()//Gets the group that he belongs to by thread object
      • public final String getName ()//through Thread Group object Get the name of his group
    • We can also set the thread to group
      • 1,threadgroup (String name) to create a thread group object and assign it a name
      • 2, creating a line Path Object
      • 3,thread (Threadgroup?group, Runnable?target, String?name)  
      • 4, set the priority of the whole group or daemon
      • B: Case demo
        • thread group usage, default is main thread group
  •   myrunnable mr = New Myrunnable (); thread T1 = new Thread (MR, "Zhang San"); Thread t2 = new Thread (MR, "John Doe");//Get thread Group//thread class inside Method: Public final Threadgroup Getthreadgroup () threadgroup TG1 = T1.getthrea DGroup (); Threadgroup TG2 = T2.getthreadgroup ();//method inside the 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: The thread by default belongs to the main thread group//through the following test, you should be able to see that, under the circumstances, all threads belong to the same group SYSTEM.OUT.PRINTLN (
     Thread.CurrentThread (). Getthreadgroup (). GetName ());  
    • Set Thread GROUP by itself
  • // ThreadGroup(String name)ThreadGroup tg = new ThreadGroup("这是一个新的组");MyRunnable mr = new MyRunnable();// Thread(ThreadGroup group, Runnable target, String name)Thread t1 = new Thread(tg, mr, "张三");Thread t2 = new Thread(tg, mr, "李四");System.out.println(t1.getThreadGroup().getName());System.out.println(t2.getThreadGroup().getName());//通过组名称设置后台线程,表示该组的线程都是后台线程tg.setDaemon(true);
8. Multithreading (five states of threads)
    • Look at the picture and talk
    • New, ready, running, blocking, dead
9. Multithreading (Overview and use of thread pool)
  • A: Thread Pool Overview
    • Program startup a new thread cost is relatively high because it involves interacting with the operating system. Using a thread pool can improve performance, especially when you want to create a lot of short-lived threads in your program. Line constructor Each thread code ends and does not die, but returns to the thread pool again to become idle, waiting for the next object to be used. Before JDK5, we had to implement our own thread pool manually, starting with JDK5, the Java built-in support thread pool
  • B: Overview of the use of the built-in thread pool
    • JDK5 added a executors factory class to generate the thread pool, there are several ways
      • public static Executorservice newfixedthreadpool (int nthreads)
      • public static Executorservice Newsinglethreadexecutor ()
      • The return value of these methods is the Executorservice object, which represents a thread pool that can execute runnable objects or the threads represented by callable objects. It provides the following methods
      • Future<?> Submit (Runnable Task)
      • Future submit (callable Task)
    • Steps to use:
      • To create a thread pool object
      • Creating an Runnable instance
      • Submitting Runnable Instances
      • Close the thread pool
    • C: Case Demo
      • It was submitted by runnable.
  • // public static ExecutorService newFixedThreadPool(int nThreads)ExecutorService pool = Executors.newFixedThreadPool(2);// 可以执行Runnable对象或者Callable对象代表的线程pool.submit(new MyRunnable());pool.submit(new MyRunnable());//结束线程池pool.shutdown();
10. Multithreading (How to implement multithreaded programs 3)
    • It was submitted by callable.

    • // 创建线程池对象ExecutorService pool = Executors.newFixedThreadPool(2);// 可以执行Runnable对象或者Callable对象代表的线程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);// 结束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;    }}
    • Ways to implement multithreaded programs 3 benefits and drawbacks

      • Benefits:

        • Can have a return value
        • can throw an exception
      • Disadvantages:

        • The code is more complex, so it's generally not
11, design mode (simple Factory mode overview and use)
    • A: Overview of the Simple factory model
      • Also called the static Factory method pattern, which defines a specific factory class that is responsible for creating instances of some classes
    • B: Advantages
      • Clients do not need to be responsible for the creation of objects, thus clarifying the responsibilities of each class
    • C: Disadvantages
      • 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, it is necessary to constantly modify the factory class, not conducive to later maintenance
    • D: Case Demo
      • Animal abstract class: Public abstract Animal {public abstract void Eat ();}
      • Specific Dog class: public class Dog extends Animal {}
      • Specific CAT class: public class Cat extends Animal {}
      • At first, each specific content in the test class is created by itself, but the task of creating the object, if it's troublesome, requires someone to do it, so we know a special class to create the object.
    • public class AnimalFactory {    private AnimalFactory(){}    //public static Dog createDog() {return new Dog();}    //public static Cat createCat() {return new Cat();}    //改进    public static Animal createAnimal(String animalName) {        if(“dog”.equals(animalName)) {}        else if(“cat”.equals(animale)) {        }else {            return null;        }    
12. Design pattern (Overview and use of factory method mode)
    • A: Overview of Factory method models
      • In factory method mode, the abstract factory class is responsible for defining the interfaces that create objects, and the creation of specific objects is implemented by the concrete classes that inherit the abstract factory.
    • B: Advantages
      • The client does not need to be responsible for the creation of objects, thus clarifying the responsibilities of each class, if there are new objects added, only need to add a specific class and the specific factory class, do not affect the existing code, late maintenance easy, enhance the system extensibility
    • C: Disadvantages
      • Additional writing code required, increased workload
    • D: Case Demo
    • 动物抽象类:public abstract Animal { public abstract void eat(); }工厂接口:public interface Factory {public abstract Animal createAnimal();}具体狗类:public class Dog extends Animal {}具体猫类:public class Cat extends Animal {}开始,在测试类中每个具体的内容自己创建对象,但是,创建对象的工作如果比较麻烦,就需要有人专门做这个事情,所以就知道了一个专门的类来创建对象。发现每次修改代码太麻烦,用工厂方法改进,针对每一个具体的实现提供一个具体工厂。狗工厂:public class DogFactory implements Factory {    public Animal createAnimal() {…}        }猫工厂:public class CatFactory implements Factory {    public Animal createAnimal() {…}        }  
13, GUI (How to create a window and display)
    • Graphical user Interface (GUI).
    • Frame  f = new Frame(“my window”);f.setLayout(new FlowLayout());//设置布局管理器f.setSize(500,400);//设置窗体大小f.setLocation(300,200);//设置窗体出现在屏幕的位置f.setIconImage(Toolkit.getDefaultToolkit().createImage("qq.png"));f.setVisible(true);
14. GUI (layout manager)
    • FlowLayout (Streaming layout manager)
      • Ordered from left to right.
      • Panel default layout manager.
    • BorderLayout (Boundary layout manager)
      • East, south, west, north, middle
      • The default layout manager for frame.
    • GridLayout (Grid layout manager)
      • Matrix of rules
    • CardLayout (Card layout manager)
      • Options tab
    • GridBagLayout (Grid package layout manager)
      • Non-rule matrices
15. GUI (Form monitoring)
Frame f = new Frame("我的窗体");//事件源是窗体,把监听器注册到事件源上//事件对象传递给监听器f.addWindowListener(new WindowAdapter() {          public void windowClosing(WindowEvent e) {                     //退出虚拟机,关闭窗口        System.exit(0);    }});
16, GUI (mouse monitoring) 17, GUI (keyboard monitoring and keyboard events) 18, GUI (action monitoring)19. Design mode (adapter design mode)
    • A. What is an adapter
      • When using the listener, you need to define a class event listener interface.
      • Usually there are multiple methods in the interface, but it's not necessarily all in the program, but it has to be rewritten, which is tedious.
      • The adapter simplifies these operations by simply inheriting the adapter when we define the listener, and then overriding the required methods.
    • B. Adapter principle
      • The adapter is a class that implements the listener interface, and all the 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 because the class object is created.
      • The goal is to simplify the programmer's operation, to define the listener to inherit the adapter, only to rewrite the required methods.
20, GUI (need to know)
    • Event handling
      • Event: An action for the user
      • Event Source: The component being manipulated
      • Listener: An object of a custom class, implements the listener interface, contains the event handler, adds the listener to the event source, and when the event occurs, the virtual machine automatically invokes the event-handling method in the listener.

Java EE Fundamentals (25)/multithreaded, GUI

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.