Java EE (5) thread

Source: Internet
Author: User
Tags array length thread class ticket

1. Clarify the concept of parallel and concurrency: * Parallel: Multiple CPU instances or multiple machines simultaneously execute a processing logic, is true at the same time. * Concurrency: Through the CPU scheduling algorithm, let the user appear to execute simultaneously, actually from the CPU operation level is not real at the same time. Concurrency often has a common resource in the scene, so for this common resource is often a bottleneck, we will use TPS or QPS to reflect the processing power of the system.2. Thread Creation    * Inherit thread class Create multithreaded public class Example01 {public static void main (string[] args) {        MyThread MyThread = new MyThread ();                        Create thread MyThread Thread object Mythread.start ();                Open thread while (true) {System.out.println ("Main method is running"); }}} class MyThread extends thread{publi                c void Run () {while (true) {System.out.println ("run () method of the MyThread class is running"); }}} * implement runnable interface Create thread public class Example01 {public static void        Main (string[] args) {MyThread MyThread = new MyThread ();   Thread object that creates thread MyThread threads thread = new Thread (MyThread);                          Create thread Object Thread.Start (); Turn on the thread, execute the run in the thread () method while (true) {System.out.println ("Main method is running"); }}} class MyThread implements runnable{public void run (                {while (true) {System.out.println ("run () method of the MyThread class is running"); }}} * Two ways to achieve multi-threaded comparison analysis, the implementation of runnable interface to inherit the thread class has the following significant benefits 1. You can avoid the limitations of Java single inheritance.            Java does not support multiple inheritance (subclasses cannot have more than one parent), subclasses of other classes cannot inherit the thread class, only the way to implement the Runnable interface 2. For multiple threads of the same program code to handle the same resource, separate the thread from the program code and data effectively.             * Background Process-If a thread object calls the Setdaemon (true) statement before it is started, the thread becomes a background process-the JVM notifies the background thread when the current thread ends-the process ends when only the background thread is running in the process3. Scheduling of Threads* Thread Priority--static int max_priority indicates that the highest priority of the thread is equal to the value of--static int min_priority that the lowest priority of the thread equals the value 1 --static int norm_priority indicates that the normal priority of the thread equals the value 5 * thread hibernation--thread.sleep () * Thread Concession--thread.yiel D () * thread Queue--join ()4. Multithreading Synchronization    * Thread safety-When multiple threads are accessing the same resource at the same time, it is easy to raise security issues.            * Synchronization code block class Ticket1 implements runnable{private int tickets = 10;            Define variable Assignment Object lock = new Object ();                    Defines any object that is used as the lock for a synchronous code block public void run () {while (true) {                            Synchronized (lock) {//define synchronous code block try {                        Thread.Sleep (2000);                        } catch (Interruptedexception e) {e.printstacktrace (); } if (tickets >0) {System.out.println (thread.c                        Urrentthread (). GetName () + "---sold tickets---" +tickets--);                        }else{break;        }}}}} public class Example01 {    public static void Main (string[] args) {Ticket1 ticket = new Ticket1 ();                        Create a Ticket1 object//Create and open four threads new thread (Ticket, "Thread 1"). Start ();                New Thread (Ticket, "Thread 2"). Start ();                New Thread (Ticket, "Thread 3"). Start ();            New Thread (Ticket, "Thread 4"). Start ();  }} * Synchronization method class Ticket1 implements runnable{private int tickets =            10;                        Define variable assignment public void run () {while (true) {saleticket ();                        if (tickets <=0) {break; }}}//Define a synchronization method Saleticket () private synchronized void saletic                    Ket () {if (Tickets > 0) {try {thread.sleep (2000); } catch (Interruptedexception e) {                       E.printstacktrace ();                } System.out.println (Thread.CurrentThread (). GetName () + "---sold tickets---" +tickets--);                }}} public class Example01 {public static void main (string[] args) {                Ticket1 ticket = new Ticket1 ();                        Create a Ticket1 object//Create and open four threads new thread (Ticket, "Thread 1"). Start ();                New Thread (Ticket, "Thread 2"). Start ();                New Thread (Ticket, "Thread 3"). Start ();            New Thread (Ticket, "Thread 4"). Start ();         }} * Deadlock problem 5. Multithreading Communication      * Problem Introduction: Suppose there are two threads at the same time to operate the same storage space, one thread is responsible for storing data into the storage space, the other thread is responsible for fetching the data.                        --Data storage class public class Storage {//datastore array private int[] cells = new INT[10];                        InPos indicates the array subscript at the time of deposit, Outpos indicates the array subscript private int inpos,outpos when taken out;                Define a put () method to deposit data into the array public void put (int num) {cells[inpos] = num;                System.out.println ("cells[" +inpos+ "] in the data--" +cells[inpos ");                inpos++;                if (InPos = = cells.length) InPos = 0;                When Inpos is an array length, set it to 0}//define a Get () method to remove the data from the arrays public void get () {                int data = Cells[outpos];                System.out.println ("cells[" +outpos+ "] to extract the data--" +data);                outpos++;                if (Outpos = = cells.length) Outpos = 0; Set to 0} when Outpos is an array length--Data access class public class INPUT implements Runnable {private Storage st;                        private int num;            Input (Storage st) {//receives a Storage object through the construction method this.st= St;            } @Override public void Run () {while (true) {st.put (num++);                        The num is stored in an array, after each deposit, num self-increment}} public class Output implements Runnable {            Private Storage St;            Output (Storage st) {//Receive a Storage object by construction method This.st = st;                 } @Override public void Run () {while (true) {st.get ();  }}}--Create thread public class ExampleTest02 {public static                void Main (string[] args) {Storage st = new Storage (); Create data store Object Input INPUT = new Input (ST);            Create input object incoming storage object output Output=new output (ST);                Creates an output object that passes in the storage object new Thread (input). Start ();                Turn on new thread (output). Start (); Open new Thread}} * Problem solving: The test found that the above access process is random, not in the order of rotation execution. If you need to rotate in a certain order, you need to communicate between processes-the wait (), notify (), and Notifyall () methods are provided in the object class to solve the communication problem between threads, because all classes in Java are subclasses or indirect subclasses of the object class.    Therefore, instance objects of any class can use these methods directly. --void Wait () causes the current thread to discard the synchronization lock and enter the wait until the other thread enters the synchronization lock and calls the Notify () or Notifyall () method to wake the thread so that the first call to wake up this sync lock waits for Wait (). The thread of the method--void Notifyall () wakes up this sync lock all threads calling the Wait () method public class Storage {private int[] cells = new    INT[10];            Data storage array private int inpos,outpos;                    InPos indicates the array subscript at the time of deposit, Outpos indicates that the array subscript private int count is taken out;        Number of data deposited or removed//define a put () method to deposit data into the array public synchronized void put (int num) {                        If the data is equal to the length of cells, this thread waits while (count = = cells.length) {try {                    This.wait ();                    } catch (Interruptedexception e) {e.printstacktrace ();                }} Cells[inpos] = num;                System.out.println ("cells[" +inpos+ "] in the data--" +cells[inpos ");                inpos++;                if (InPos = = cells.length) InPos = 0;                When the Inpos is an array length, it is set to 0 count++;            This.notify (); }//define a Get () method to remove data from the array public synchronized void get () {W                    Hile (count = = 0) {//If count is 0 this thread waits for try {this.wait (); } catch (Interruptedexception e) {//TODO auto-generated catch block E.P    Rintstacktrace ();                }} int data = Cells[outpos];                System.out.println ("in cells[" +outpos+ "] to extract data:" +data);                Cells[outpos] = 0;                outpos++;                if (Outpos = = cells.length) Outpos = 0;                When the Outpos is an array length, it is set to 0 count--;            This.notify ();             }} Note: If Wait (), notify (), Notifyall () method callers are not synchronous lock objects, the JVM throws Java.lang.IllegalMonitorStateException

Java EE (5) thread

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.