In Layman's Java multithreading

Source: Internet
Author: User
Tags mutex stub thread class

Processes and Threads

Process: program (Task) execution process (dynamic), holding resources (shared memory, shared files) and threads

such as QQ on our computer, if just put in there, not the process, only when you click on it to run after the start of a process.

Threads: such as QQ, can be text chat, while starting a file, which is 2 threads.

A thread is the smallest execution unit in the system, and the same process can have multiple threads, and threads share the resources of the process.

Interaction of Threads: mutual exclusion (competition) and synchronization (cooperation)

For example, in the same class, each classmate is a thread, we share public resources such as tables and chairs, blackboard, learning materials and so on. Students can communicate with each other, the relationship is mutually exclusive and synchronous. If classmate A and classmate B at the same time to use a learning material, there is a mutual exclusion, the need for a use; When the school organizes the theatrical display, the students need to cooperate with each other in order to perform excellent programs.

The first experience of Java threads

    • Java Support for threading
      • The thread class and the Runnable interface have the Run () method
    • Thread creation and startup
    • Thread Common methods

To learn more about multithreading in the Sui and Tang dynasties with the heroic interpretation of the actual project

  • According to the story outline, we need "Army-armyrunnable", "heroic character-keypersonthread", "stage-stage" these three classes;
  • /*** Military Threads * Simulates the actions of both sides of the battle *@author * */ Public classArmyrunnableImplementsRunnable {//volatile (visibility JMM, happens-before principle) ensures that threads can correctly read values written by other threads    volatile BooleanKeeprunning =true; @Override Public voidrun () {//TODO auto-generated Method Stub         while(keeprunning) {//Launch 5 Combos             for(inti=0; i<5; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "Attack each other" ["+ i +"] hit "); //Give up the CPU time, next time who attack is not necessarily! Thread.yield (); }} System.out.println (Thread.CurrentThread (). GetName ()+ "End of battle!" "); }} Public classKeypersonthreadextendsThread { Public voidrun () {System.out.println (Thread.CurrentThread (). GetName ( )+ "Start the fight!");  for(inti=0; i<10; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "Left axon right kill, attack army ... "); } System.out.println (Thread.CurrentThread (). GetName ()+ "End of battle!"); }}/*** The drama stage of the Sui and Tang kingdoms@author * */ Public classStageextendsThread { Public voidrun () {System.out.println ("Welcome to the Sui and Tang kingdoms"); Try{Thread.Sleep (5000); } Catch(interruptedexception E1) {e1.printstacktrace (); } System.out.println ("The curtain opens slowly."); Try{Thread.Sleep (5000); } Catch(interruptedexception E1) {//TODO auto-generated Catch blockE1.printstacktrace (); } System.out.println ("In the Sui Dynasty, army and peasant uprising army killed pitch darkness ..."); Armyrunnable Armytaskofsuidynasty=Newarmyrunnable (); Armyrunnable Armytaskofrevolt=Newarmyrunnable (); //To start a thread using the Runnable interfaceThread armyofsuidynasty =NewThread (Armytaskofsuidynasty, "army"); Thread Armyofrevolt=NewThread (Armytaskofrevolt, "Rebel army")); //start the thread and let both armies start fighting.Armyofsuidynasty.start ();                Armyofrevolt.start (); //The stage thread sleeps and everyone is watching the army fight.        Try{Thread.Sleep (50); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Just as the two sides are in a good fight, halfway to kill a journey to bite the gold."); Thread Mrcheng=NewKeypersonthread (); Mrcheng.setname ("Cheng Bite Gold"); System.out.println ("Cheng's ideal of biting gold is to end the war, so that people can live and live!" "); //the way the army stopped fighting and stopped threading.Armytaskofsuidynasty.keeprunning =false; Armytaskofrevolt.keeprunning=false; Try{Thread.Sleep (2000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }                //historical drama left to key figuresMrcheng.start (); Try{mrcheng.join (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println ("The end of the war, the people live in peace and contentment, Mr. Cheng realized a positive life dream, to contribute to the people"); System.out.println ("Thank you for watching the Sui and Tang kingdoms, thank you!" "); }         Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        NewStage (). Start (); }}
    View Code

  • How to properly stop a thread
    • The Stop () method is an incorrect way to stop a thread; It stops the thread, and we don't know what it's done, what work is done, and it's wrong.
    • Use Exit flag: As in the example above, keeprunning is an end flag.
    • Interrupt () Method: The original intention is not to stop the thread

Java Threading Interaction

  • The Lost Energy
    • What is a race condition (Race Condition)
      • When multiple threads access the same data (memory region) at the same time, each thread attempts to manipulate the data, causing data corruption (corrupted), which is known as a race condition.
      • as shown, when a time period, thread 1 obtains the CPU time, reads the value of Energybox[to] from main memory, and then adds 500, but has not written back to memory, the CPU time is exhausted; then thread 2 gets the CPU, The value of Read Energybox[to] is still 5000, then it operates with 900, and writes back to memory 5900, then CPU time is exhausted. And the following is a thread 1 to obtain a time slice, it calculates the above 5500 to write memory, resulting in the final memory stored in the value of 5500. And through thread 1 and thread 2 modification, the value of the final write memory of Energybox[to] should be 6400 is correct! In this way, the result of energy conservation is occurring.
      • So, how do you modify the code so that the energy becomes conserved? The
        • is mutually exclusive and synchronized to get the thread to interact correctly.
        • Mutex: Critical data can only be accessed by one thread at a time. Implementation: synchronized (intrinsic lock)
        • synchronization: All threads are caught in a wait state because some of the conditions of the resource are not satisfied, and when the conditions for accessing the resource are met, all the threads are awakened to the mutex state. Implementation: Wait ()/notify ()/notifyall ()--are all methods of object objects.
        • Wait ()/notify ()/notifyall () is not executed in the same operation on the same thread. Because synchronization refers to synchronization between multiple threads, there is no need to synchronize with only one thread !!
        • When a thread accesses a critical area (Critical section), it first obtains a lock on that critical section, and when the lock is acquired to determine whether the condition that obtains the resource is satisfied, the lock is freed when the condition is not met (so that other threads can enter the critical section) and enters wait in the Wait (Wait ()) queue on the lock object. When other threads have finished using the critical section, they will be told (Notifyall ()) All the threads in the waiting queue: the conditions in the critical section are changing, so you can start competing for lock objects.

Important Review

    • How to create the basic operations of threads and threads;
    • visibility and volatile keywords;
    • Race conditions;
    • Mutually exclusive synchronized of threads;
    • Synchronization of Threads Wait/notifyall ();

Extended

    • Java Memory Mode
      • JMM Describes how Java threads interact with memory
      • Happens-before Principles
      • Synchronized, volatile & final
    • Locks & Condition
      • A high-level implementation of the Java lock mechanism and wait conditions
      • Java.util.concurrent.locks
    • Thread-Safe
      • Atomicity and visibility
      • Java.util.concurrent.atomic
      • Synchronized & Volatile
      • Deadlocks
    • Multi-Threading Common interaction Model
      • Producer-consumer model
      • Read-write Lock Model
      • Future model
      • Worker Thread Model
    • Concurrent programming tools in JAVA5
      • Java.util.concurrent
      • Thread Pool Excecutorservice
      • Callable & Future
      • Blockingqueue

In Layman's Java 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.