Java EE Basics (24)/multithreading

Source: Internet
Author: User
Tags ticket

1, multithreading (Introduction of multithreading)
    • 1. What is a thread
      • A thread is a path that a program executes, and a process can contain multiple threads
      • Multi-threaded concurrent execution can improve the efficiency of the program and can do multiple tasks at the same time
    • 2. Multi-Threaded application scenarios
      • Red spider sharing screen to multiple computers at the same time
      • Thunderbolt open multiple threads to download together
      • QQ at the same time and many people together video
      • The server processes multiple client requests at the same time
2. Multithreading (the difference between multithreading parallelism and concurrency)
    • Parallel is two tasks at the same time, that is, a task is carried out at the same time, B task is also in progress. (Multi-core CPU required)
    • Concurrency means that two tasks are requested to run, and the processor can only be subject to a single task, the two tasks are scheduled to take turns, because the time interval is short, making people feel that both tasks are running.
    • For example, I chat with two netizens, left hand operation a computer with a chat, while the right hand with another computer with B chat, this is called parallel.
    • If you use a computer I send a message first, and then immediately give a message to B, and then chat with a, and then chat with B. This is called concurrency.
3, multi-threaded (Java program running principle and JVM startup is multi-threaded?)
    • A:java Program Operation principle

      • The Java command launches the Java Virtual machine, starting the JVM, which is equivalent to launching an application, that is, initiating a process. The process automatically starts a "main thread" and then the main thread calls the main method of a class.
    • Is the startup of the B:JVM multi-threaded?

      • The JVM startup starts at least the garbage collection thread and the main thread, so it is multithreaded.
4. Multithreading (How to implement multithreaded programs 1)
    • 1. Inherit thread

      • Define class inheritance Thread
      • Overriding the Run method
      • Write what the new thread is going to do in the Run method
      • To create a thread object
      • Opens a new thread, and the Run method is automatically executed internally
      • public class Demo2_Thread {    /**     * @param args     */    public static void main(String[] args) {        MyThread mt = new MyThread();                           //4,创建自定义类的对象        mt.start();                                             //5,开启线程        for(int i = 0; i < 3000; i++) {            System.out.println("bb");        }    }}class MyThread extends Thread {                                 //1,定义类继承Thread    public void run() {                                         //2,重写run方法        for(int i = 0; i < 3000; i++) {                         //3,将要执行的代码,写在run方法中            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa");        }    }}
5. Multithreading (How to implement multithreaded programs 2)
  • 2. Implement Runnable

    • Defining a class implementation runnable interface
    • Implementing the Run Method
    • Write what the new thread is going to do in the Run method
    • Creating a child class object for a custom runnable
    • Create thread object, incoming runnable
    • Call Start () to open a new thread, the internal automatically calls the Runnable run () method

      public class Demo3_Runnable {    /**     * @param args     */    public static void main(String[] args) {        MyRunnable mr = new MyRunnable();                       //4,创建自定义类对象        //Runnable target = new MyRunnable();        Thread t = new Thread(mr);                              //5,将其当作参数传递给Thread的构造函数        t.start();                                              //6,开启线程        for(int i = 0; i < 3000; i++) {            System.out.println("bb");        }    }}class MyRunnable implements Runnable {                          //1,自定义类实现Runnable接口    @Override    public void run() {                                         //2,重写run方法        for(int i = 0; i < 3000; i++) {                         //3,将要执行的代码,写在run方法中            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa");        }    }}
6, multi-thread (realize runnable principle)
    • View Source
      • 1, look at the constructor of the thread class, passing a reference to the Runnable interface
      • 2, use the init () method to find the target assignment of the passed target to the member variable
      • 3, look at the Run method and find out in the Run method that the Run method of the Runnable interface subclass object is called if Target is not null
7, Multi-threaded (two different ways)
    • See the difference between the source code:

      • A. Inherit thread: Because the subclass overrides the thread class's run (), when Start () is called, the Run () method of the subclass is searched directly
      • B. Implement runnable: A reference to the runnable is passed in the constructor, the member variable remembers it, and the start () call to the run () method internally determines whether the reference to the member variable runnable is empty, and does not empty compile-time view of the runnable run (). Run-time execution is a subclass of the run () method
    • Inherit thread

      • The advantage is that the methods in the thread class can be used directly, and the code is simple
      • The disadvantage is that if you already have a parent class, you can't use this method
    • Implementing the Runnable Interface
      • The advantage is that even if the thread class you define has a parent class, it doesn't matter, because the parent class can also implement the interface, and the interface can be implemented more
      • The disadvantage is that you cannot use the method in thread directly before you get to the thread object, the code is complex
8, Multi-threaded (anonymous inner class two ways to implement threading)
    • Inherit the thread class

      new Thread() {                                                  //1,new 类(){}继承这个类    public void run() {                                         //2,重写run方法        for(int i = 0; i < 3000; i++) {                         //3,将要执行的代码,写在run方法中            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa");        }    }}.start();
    • Implementing the Runnable Interface

      new Thread(new Runnable(){                                      //1,new 接口(){}实现这个接口    public void run() {                                         //2,重写run方法        for(int i = 0; i < 3000; i++) {                         //3,将要执行的代码,写在run方法中            System.out.println("bb");        }    
9. Multithreading (get first name and set name)
  • 1. Get the name
    • Gets the name of the thread object through the GetName () method
  • 2. Set name

    • Pass constructor to pass in string type name
    •   new Thread ("xxx") {public void run () {        for (int i = 0; i < i++) {System.out.println (This.getname () + ".... aaaaaaaaaaaaaaaaaaaaaaa"); }}}.start (); New Thread ("yyy") {public void run () {for (int i = 0; i <; i++) {SYSTEM.O        Ut.println (This.getname () + ".... bb"); }}}.start ();  
    • to set the name of a thread object by using the SetName (String) method
    •   Thread t1 = new Thread () {public void Ru N () {for (int i = 0; i < i++) {System.out.println (This.getname () + ".... aaaaaaaaaaaaaaaaaaaaaa        A "); }    }}; Thread t2 = new Thread () {public void run () {for (int i = 0; i <; i++) {System.out.println (        This.getname () + ".... bb");
       }}};t1.setname ("Sister Furong"); T2.setname ("Sister Feng"); T1.start (); T2.start ();  
10, multithreading (Gets the object of the current thread)
    • Thread.CurrentThread (), the main thread can also get

      • new Thread(new Runnable() {    public void run() {        for(int i = 0; i < 1000; i++) {            System.out.println(Thread.currentThread().getName() + "...aaaaaaaaaaaaaaaaaaaaa");        }    }}).start();new Thread(new Runnable() {    public void run() {        for(int i = 0; i < 1000; i++) {            System.out.println(Thread.currentThread().getName() + "...bb");        }    }}).start();Thread.currentThread().setName("我是主线程");                    //获取主函数线程的引用,并改名字System.out.println(Thread.currentThread().getName());       //获取主函数线程的引用,并获取名字
11. Multithreading (dormant threads)
    • Thread.Sleep (milliseconds, nanoseconds), controls the current thread sleeps for several milliseconds 1 seconds = 1000 milliseconds 1 seconds = 1000 * 1000 * 1000 nanoseconds 1000000000

          new Thread() {        public void run() {            for(int i = 0; i < 10; i++) {                System.out.println(getName() + "...aaaaaaaaaaaaaaaaaaaaaa");                try {                    Thread.sleep(10);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }    }.start();    new Thread() {        public void run() {            for(int i = 0; i < 10; i++) {                System.out.println(getName() + "...bb");                try {                    Thread.sleep(10);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }    }.start();
12. Multithreading (daemon thread)
    • Setdaemon (), sets a thread as the daemon thread, which is not executed separately, and exits automatically when other non-daemon threads have finished executing

      • Thread t1 = new Thread() {    public void run() {        for(int i = 0; i < 50; i++) {            System.out.println(getName() + "...aaaaaaaaaaaaaaaaaaaaaa");            try {                Thread.sleep(10);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }};Thread t2 = new Thread() {    public void run() {        for(int i = 0; i < 5; i++) {            System.out.println(getName() + "...bb");            try {                Thread.sleep(10);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }};t1.setDaemon(true);                     //将t1设置为守护线程t1.start();t2.start();
13. Multithreading (join thread)
  • Join (), the current thread pauses, waits for the specified thread to finish executing, and the current thread resumes
  • Join (int), which can wait for a specified millisecond to continue after

    • final Thread t1 = new Thread() {    public void run() {        for(int i = 0; i < 50; i++) {            System.out.println(getName() + "...aaaaaaaaaaaaaaaaaaaaaa");            try {                Thread.sleep(10);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }};Thread t2 = new Thread() {    public void run() {        for(int i = 0; i < 50; i++) {            if(i == 2) {                try {                    //t1.join();                        //插队,加入                    t1.join(30);                        //加入,有固定的时间,过了固定时间,继续交替执行                    Thread.sleep(10);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            System.out.println(getName() + "...bb");        }    }};t1.start();t2.start();
14. Multithreading (comity thread)
    • Yield yields a CPU
15, multi-threaded (set the priority of the thread)
    • SetPriority () Sets the priority of the thread
16. Multithreading (Synchronous code block)
    • 1. When synchronization is required
      • when multithreading is concurrent and there are multiple pieces of code executing simultaneously, we expect the CPU to not switch to another thread during the execution of a piece of code. This will require synchronization.
      • If two pieces of code are synchronized, only one period can be executed at a time, and no additional piece of code will be executed until the end of the code execution.
    • 2. Synchronizing code blocks

      • use the Synchronized keyword plus a lock object to define a piece of code, which is called a synchronous code block
      • Multiple synchronization blocks If you use the same lock object, that They're just synchronized.

          class Printer {Demo d = new demo (); public static void Print1 () {synchronized (d) {//Lock object can be any object, but the locked code needs to be guaranteed to be the same lock and cannot be used with an anonymous object Syst            Em.out.print ("Black");            System.out.print ("Ma");            System.out.print ("Cheng");            System.out.print ("preface");            System.out.print ("member");        System.out.print ("\ r \ n");            }} public static void Print2 () {synchronized (d) {System.out.print ("pass");            System.out.print ("Chi");            System.out.print ("broadcast");            System.out.print ("Guest");        System.out.print ("\ r \ n"); }    }}
17. Multithreading (synchronous method)
    • Use the Synchronized keyword to decorate a method in which all the code in the method is synchronized

      class Printer {    public static void print1() {        synchronized(Printer.class){                //锁对象可以是任意对象,但是被锁的代码需要保证是同一把锁,不能用匿名对象            System.out.print("黑");            System.out.print("马");            System.out.print("程");            System.out.print("序");            System.out.print("员");            System.out.print("\r\n");        }    }    /*     * 非静态同步函数的锁是:this     * 静态的同步函数的锁是:字节码对象     */    public static synchronized void print2() {          System.out.print("传");        System.out.print("智");        System.out.print("播");        System.out.print("客");        System.out.print("\r\n");    }}
18. Multithreading (thread safety issues)
  • Thread safety issues can occur when multiple threads concurrently manipulate the same data
  • The use of synchronization technology can solve this problem, the operation of the code to synchronize the data, not to work with multiple threads

        public class Demo2_synchronized {/** * @param args * Demand: railway ticket sales, altogether 100, through four windows sold out.            */public static void main (string[] args) {Ticketsseller T1 = new Ticketsseller ();            Ticketsseller t2 = new Ticketsseller ();            ticketsseller t3 = new Ticketsseller ();            ticketsseller T4 = new Ticketsseller ();            T1.setname ("Window 1");            T2.setname ("Window 2");            T3.setname ("Window 3");            T4.setname ("Window 4");            T1.start ();            T2.start ();            T3.start ();        T4.start ();        }} class Ticketsseller extends Thread {private static int tickets = 100;        Static Object obj = new Object ();        Public Ticketsseller () {super ();        } public Ticketsseller (String name) {super (name); The public void, run () {while (true) {synchronized (obj) {if (tickets &lt                     ; = 0)    Break                        try {thread.sleep (10);//thread 1 sleeps, thread 2 sleeps, thread 3 sleeps, thread 4 sleeps} catch (Interruptedexception e) {                    E.printstacktrace (); } System.out.println (GetName () + "...                This is the first "+ tickets--+" ticket "); }            }        }    }
19, multi-threaded (railway station ticket sales example with the implementation of the Runnable interface)20. Multi-threaded (deadlock)
    • If synchronization code is nested and the same lock is used, the deadlock may occur

      • Try not to nest using

          private static String S1 = "Chopsticks             Child Left ";p rivate static String s2 =" chopstick right ";p ublic static void Main (string[] args) {new Thread () {public void run () { while (true) {synchronized (S1) {System.out.println (GetName () + "...                    Get "+ S1 +" Wait "+ s2); Synchronized (S2) {System.out.println (GetName () + "...                    Get "+ s2 +" open to eat ");    }}}}}.start (); New Thread () {public void run () {while (true) {synchronized (s2) {Sy Stem.out.println (GetName () + "...                    Get "+ s2 +" Wait "+ S1); Synchronized (S1) {System.out.println (GetName () + "...                    Get "+ S1 +" open to eat ");
          }}}}}.start ();}  
21. Multithreading (Previous thread-safe Class review)
    • A: Review the thread safety issues previously mentioned
      • See Source: vector,stringbuffer,hashtable,collections.synchroinzed (XXX)
      • Vectors are thread-safe and ArrayList are thread insecure
      • StringBuffer is thread-safe, StringBuilder is thread insecure
      • Hashtable is thread-safe, HashMap is thread insecure

Java EE Basics (24)/multithreading

Related Article

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.