30. Multithreading

Source: Internet
Author: User
Tags stub thread class thread stop ticket

Process: A program in progress
Each process execution has an execution order, which is an execution path, or a control unit
Thread: A separate control unit in the process in which the thread controls the execution of the process.
There is at least one thread in a process.

The Java JVM will start with a process Java.exe
At least one thread in the process is responsible for the execution of the Java program.
And the code that this thread runs on is in the main method.
This thread is called the primary thread.

Extensions: More details indicate that JVM,JVM initiates more than one thread, as well as a thread responsible for the garbage collection mechanism.

1. How do you customize a thread in your custom code?
By looking at the API, Java has provided a description of what the thread is like, and the thread class

First way to create a thread: Create thread
Steps:
1. Define class inheritance Thread
2. The Run method in the replication thread class
Purpose: Store the custom code in the Run method and let the thread run.
3. Call the thread's Start method, which has two functions:
1) Start thread
2) Call the Run method

Finding the results of a run is different every time.
Because more than one thread gets the execution of the CPU, the CPU executes to whom, who runs.
It is clear that at some point there can be only one program executing (with the exception of multicore). The CPU is doing a quick switchover to achieve the effect that appears to be running simultaneously.
We can image the multi-threaded running behavior in each other Snatch cup execution right.

This is a feature of multithreading: Randomness. Who grabs who to execute. As for how long, the CPU decides.

Why overwrite the Run method?
The thread class is used to describe threads. The class defines a feature that stores the code that the thread wants to run. This function is the Run method.
In other words, the Run method in the thread class is used to store the code that the thread is running.

 Public classthread_02 { Public Static voidMain (string[] args) {//TODO auto-generated Method StubDemo d=NewDemo ();//create a thread.D.start ();//Open the thread and execute the thread's Run methodD.run ();//only the object calls the method, and the thread is created and not running.                  for(inti=0;i<60;i++) {System.out.println ("Hello World" +i); }            }}classDemoextendsthread{ Public voidrun () { for(inti=0;i<60;i++) {System.out.println ("Demo Run" +i); }    }}

Practice
Create two threads, and run alternately on the main thread

The original thread has its own default name. Obtained by. GetName (), thread-number This number starts with 0.

The thread initializes with a name, and the parent class completes the assignment when the constructor is used, directly with super (name).

Static thread CurrentThread (): Gets the current thread object
GetName (): Gets the name of the thread
Set thread Name: SetName or constructor

 Public classthread_03 { Public Static voidMain (string[] args) {//TODO auto-generated Method StubTest t1=NewTest ("One"); Test T2=NewTest ("both");        T1.start ();                T2.start ();  for(inti=0;i<60;i++) {System.out.println ("Main------" +i); }    }}classTestextendsthread{//private String name;Test (String name) {//This.name=name;        Super(name); }     Public voidrun () { for(inti=0;i<60;i++) {System.out.println ( This. GetName () + "---test run---" +i); }    }}

Requirements: A simple ticket-selling procedure.
Multiple Windows sell tickets at the same time.
Static decoration, member variable sharing.

 Public classticket_04 { Public Static voidMain (string[] args) {//TODO auto-generated Method StubTicket t1=NewTicket (); Ticket T2=NewTicket (); Ticket T3=NewTicket (); Ticket T4=NewTicket ();           T1.start ();        T2.start ();        T3.start ();    T4.start (); }}classTicketextendsthread{Private Static inttick=100;  Public voidrun () { while(true){            if(tick>0) {System.out.println (CurrentThread (). GetName ()+ "... sale:" +tick--); }        }    }}

Requirements: A simple ticket-selling procedure.
Multiple Windows sell tickets at the same time.

Second way to create a thread: implementing the Runnable Interface

Steps:
1. Define class implementation Runnable interface
2. Overwrite the Run method in the Runnable interface
Store the code that the thread will run in the Run method.
3. Thread objects are established through the thread class.
4. Pass the subclass object of the Runnable interface as the actual parameter to the constructor of the thread class.
Why pass the subclass object of the Runnable interface to the thread's constructor?
Because the object that the custom run method belongs to is the subclass object of the Runnable interface, let the thread execute the Run method of the specified object.
So to have the thread execute the Run method of the specified object, you must specify the object to which the Run method belongs.
5. Call the Start method of the thread class to open the thread and invoke the Run method of the Runnable interface subclass.

What is the difference between the way of implementation and the way of inheritance?
Benefits of implementation: avoids the limitations of single inheritance and suggests implementing implementations when defining threads
Difference:
Inherit thread: The threading code is stored in the threads subclass Run method.
Implement runnable: County code is stored in the subclass of the interface Run method.


Through analysis, print out 0-1-2 of the wrong ticket.
There is a security issue with multithreaded operation.
The cause of the problem:
When multiple statements are working on the same thread to share data, a thread executes only a portion of multiple statements,
has not finished executing, another thread participates in the execution, causing the error of sharing the data.
(tick=1, Thread 0 1 2 3 are eligible for execution, then execute separately, print 1 0-1-2)
Workaround:
Statements that share data on multiple operations can only have one thread complete. During execution, other threads are not allowed to participate in execution.

Java provides a professional solution for multi-threaded security issues. is to synchronize the code block.
Synchronized (object) {
Code that needs to be synchronized (contribution data-related code)
}

objects are like locks. The thread holding the lock can be executed in sync. A thread that does not hold a lock does not get in even if it gets CPU execution because no lock is acquired.
Prerequisites for synchronization:
1. There must be two or more than two threads.
2. You must use the same lock for multiple threads.
You must ensure that only one thread in the synchronization is running.
Benefits: Solves the problem of multithreading security.
Cons: Multiple threads need to determine the lock and consume more resources.

 Public classrunnable_05 { Public Static voidMain (string[] args) {//TODO auto-generated Method StubTicket1 t=NewTicket1 (); Thread T1=NewThread (t);//A thread was createdThread t2=NewThread (t); Thread T3=NewThread (t); Thread T4=NewThread (t);        T1.start ();        T2.start ();        T3.start ();    T4.start (); }}classTicket1Implementsrunnable{Private inttick=100; Object o=NewObject ();  Public voidRun () {//An exception in an interface can only try         while(true){            synchronized(o) {if(tick>0){                    Try{Thread.Sleep (10); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "... sale:" +tick--); }            }                    }    }}

Demand:
The bank has a vault, with two depositors saving 300 yuan each, saving 100 and saving 3 times.
Purpose: Does the program have a security problem, and if so, how to solve it?
How do I find a problem?
1. Identify which code is running the code in multithreaded mode.
2. Clearly shared data
3. Define which statements in multithreaded run code are operations that share data.

 Public classsyn_function_06 { Public Static voidMain (string[] args) {//TODO auto-generated Method StubCus c=NewCus (); Thread T1=NewThread (c); Thread T2=NewThread (c);        T1.start ();    T2.start (); }}classbank{Private intsum; Object o=NewObject (); /*Public void Add (int n) {///Sync code block synchronized (o) {sum=sum+n;            try {thread.sleep (10);            } catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();        } System.out.println ("sum=" +sum); }    }*/        //Change to sync function     Public synchronized voidAddintN) {Sum=sum+N; Try{Thread.Sleep (10); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println ("Sum=" +sum); }}classCusImplementsrunnable{PrivateBank b=NewBank ();  Public voidrun () { for(intx=0;x<3;x++) {B.add (100); }    }}

Which lock does the synchronization function use?
The function needs to be called by the object, and the function has a reference to the owning object, which is this. So the lock used by the sync function is this.
Ready to validate through the program.
One thread is in the synchronization code block, and one thread is in the synchronization function. Are executing the ticket sales action.

What is the lock used if the synchronization function is modified by a static function?
By verification, Discovery is no longer this. This cannot be defined in a static method.
When static into memory, there is no such object in memory, but there must be a corresponding bytecode file for that class.
A static synchronization method that uses a lock that is the byte-code file object of the class in which the method resides, class name. class

 Public classthislockdemo_07 { Public Static voidMain (string[] args) {//TODO auto-generated Method StubTick t=NewTick (); Thread T1=NewThread (t); Thread T2=NewThread (t);  T1.start (); //Not necessarily executed immediately, the main thread may be executed instantaneously at the same time        Try{Thread.Sleep (10);//let the main thread stop for a moment}Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } T.flag=false;    T2.start (); }}classTickImplementsrunnable{Private Static inttick=100; Booleanflag=true;  Public voidRun () {//The method adds synchronized, only one thread comes in, crazy print, because the other threads don't come in        if(flag) { while(true){                synchronized(/* This*/Tick.class) {//If you do not use the same lock, there will be 0 wrong votes, this is the synchronization function is also used by the lock                    if(tick>0){                        Try{Thread.Sleep (10); System.out.println (Thread.CurrentThread (). GetName ()+ "... code:" +tick--); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }                    }                }            }        }Else{             while(true) {show (); }        }    }    /*Public synchronized void Show () {if (tick>0) {try {thread.sleep (10);            System.out.println (Thread.CurrentThread (). GetName () + "... show:" +tick--);            } catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); }        }    }*/        //if the static synchronization function     Public Static synchronized voidShow () {if(tick>0){            Try{Thread.Sleep (10); System.out.println (Thread.CurrentThread (). GetName ()+ "... show:" +tick--); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }    }}

30. 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.