The first knowledge of Java learning notes multithreading

Source: Internet
Author: User
Tags thread class ticket

First Knowledge multithreading

I. Awareness of the process:

1. Understanding of the process:

Process can be understood as the task in progress, that is, the program is running, the process is divided into two, one is the foreground process, that is, we are very intuitive to see, the other is the background process, is the operating system to start some (system-level processes), each process will occupy a certain amount of CPU and memory resources;

For example: We open the Window Task Manager can see a lot of processes, there are users open, there are operating system-initiated processes

2. Scheduling of processes:

So many processes, how does the CPU work?

Using time slice Rotation method

Two. Threading Awareness

1. Threading Comprehension

A thread is an executing body that runs inside a process

(1). A process can create multiple threads

(2). Processes and threads compete for CPU, and the probabilities are equal

(3). Thread dependent process, cannot exist independently

(4). In Java, a process has at least one thread, and the main method is called the main path;

We can output a 1/0 in the main method of Java;

(5). The process or thread has priority, high priority can get more time slice and CPU execution right

(6). Preemptive scheduling: Priority-high processes can preempt CPU execution with low priority

2. Why do you want to do multi-threading?

Reason:

(1). Allow multiple programs to execute simultaneously

(2). Improve the execution efficiency of the program

Three. Creation of threads

1. Way one: inheriting the thread class

Small Demo:

1 // define a class that inherits the thread class 2  Public  class  MyThread  extends  Thread {34     //  Override the thread class's run    method 5public     void  run () {6         System.out.print ("I am a sub-thread")  ; 7     }8 }

  

1  Public class Demo {2      Public Static void Main (string[] args) {3         // Create a subclass object, and then call Start (); Method 4         MyThread mt=New  MyThread (); 5         Mt.start (); 6     }7 }

2. Mode two: Realize Runnable interface

Small Demo:

// implementing the definition of a class  Public class Myrunnableimpl  implements  Runnable {    // Define a Runnable implementation class, and then override the Run method     @Override    publicvoid  run () {        //  Write the function code here     }}
1  Public classDemo {2     //Using Code3      Public Static voidMain (string[] args) {4         //New A Runnable implementation class object5Myrunnableimpl my=NewMyrunnableimpl ();6         //the implementation class object is then passed into the constructor method of the thread class, and the thread class object is created7         //call the Thread object Start () method to open Threads8         NewThread (My). Start ();9     }Ten}

Four. Thread safety

1. Causes of thread safety problems:

Thread-safety issues occur when multiple threads are accessing shared resources

Take a look at a case: multi-window sell movie ticket case

1 classTicketImplementsRunnable {2     //number of movie tickets3     private static  intticket=100;4 @Override5      Public voidrun () {6          while(true){7             if(ticket>0){8                 //scenarios for simulating network latency9                 Try {TenThread.Sleep (50); One}Catch(interruptedexception e) { A                     //TODO auto-generated Catch block - e.printstacktrace (); -                 } the                 //sale of votes (minus and minus operations) -System.out.println ("+ticket--+" Ticket "is being sold"); -             } -         } +     } - } +  Public classDemo { A      Public Static voidMain (string[] args) { at         //new an implementation class object -Ticket t=NewTicket (); -         //Create 3 threads to sell a movie ticket -         NewThread (t). Start (); -         NewThread (t). Start (); -         NewThread (t). Start (); in          -     } to}

This is where the problem arises:

    

The explanation for this problem arises:

When a movie ticket is left, the thread with the CPU execution runs to the while (true), passes smoothly, and then runs Sleep (), when the thread is plugged in, the movie ticket or the 1,cpu execution is taken by another thread, and it runs to the while ( true), which passes smoothly, then runs sleep (); CPU execution is snatched by a third thread, the same runs, and the last thread that wakes up continues to execute the following code. The phenomenon of negative votes is generated.

2. Solutions for thread safety issues:

(1). Synchronizing code blocks

    

1      2      //defines an object as a lock object3      StaticObject obj =NewObject ();4      /*5 Synchronizing code blocks:6 Parameters: Lock Object7 1:java Any object can be used as a lock object8 2: All threads must share this lock object (only one copy of the object)9 synchronized (mutex) {Ten //Store code that needs to be locked One         } A       */ -      -     //implement code to sell tickets the @Override -      Public voidrun () { -          -          while(true){ +             synchronized(obj) {//Locking -                 if(Tickets > 0 ){ +                     //simulate the delay of a network A                     Try{Thread.Sleep (50);}Catch(Exception e) {} atSystem.out.println ("For sale" + tickets--+ "Ticket"); -                 } -}//Unlock -         } -}

(2). Synchronization method

1     /*2 * Synchronization method: Lock the whole method3      * 4 * 1: The lock object of the synchronization method is this, here the this must be the same5 * 2: The lock object of the static method is: class name.6      */7     /*8 * The difference between synchronous code blocks and synchronous methods:9 * 1: Sync code block to lock any piece of codeTen * 2: The synchronization method is to lock the whole method One      *   A      *   - * 3: Objects that synchronize code blocks can be specified by themselves - * 4: The lock object of the synchronization method must be this the      */ -      Public synchronized voidmethod () { -         if(Tickets > 0) { -             //simulate the delay of a network +             Try { -Thread.Sleep (50); +}Catch(Exception e) { A             } atSystem.out.println ("For sale" + tickets--+ "Ticket"); -         } -     } -  -     //implement code to sell tickets - @Override in      Public voidrun () { -  to          while(true) { + method (); -         } the}

(3). Sync Lock

1 /*2 * Sync Lock:3 * Lock Interface:4 * Reentrantlock Implementation class:5 * Lock (); locking6 * unlock (); Unlock7      */8     9     //1: Create lock ObjectTenReentrantlock RT =NewReentrantlock (); One      A      -     //implement code to sell tickets - @Override the      Public voidrun () { -  -          while(true) { -             //2: Lock in the right place + Rt.lock (); -              +             if(Tickets > 0) { A                 //simulate the delay of a network at                 Try { -Thread.Sleep (50); -}Catch(Exception e) { -                 } -System.out.println ("For sale" + tickets--+ "Ticket"); -             } in             //3: Unlock in the right place - Rt.unlock (); to         } +}

Five. Status of the thread

  

The first knowledge of Java learning notes multithreading

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.