Javase basics 6: Multithreading

Source: Internet
Author: User

------- Android training, Java training, and hope to communicate with you! ----------

Two ways to create a thread: Inherit the Thread class or implement the runnable interface 1: Inherit the Thread class.

Steps:
1. Define a class to inherit the Thread class.
2. Override the run method in the Thread class.
3. directly create a thread subclass object to create a thread.
4. Call the start method to enable the thread and call the run method of the thread.
Get the thread name through the getname () method. default name: thread-number (starting from 0)
2. Implement the runnable interface.

1. Define the class to implement the runnable interface.
2. overwrite the run () method of the interface and encapsulate the task code of the thread into the run () method.
3. Create a thread object and pass the subclass object of the runnable interface as a parameter of the thread class constructor.
4. Call the START () method of the thread object to enable the thread.

Thread: If there is no parent class, you can inherit the thread
Runnable: avoids the limitation of single inheritance. We recommend that you use the interface to create a thread.

Cause of thread security problem:

1. When multiple threads operate on shared data.
2. There are multiple codes used to operate on shared data.
Other threads can be involved in a thread operation.

Thread status conversion

Synchronized synchronization lock:

Synchronous Code block: A lock is an object;
Synchronous function: the lock is actually this;
Static synchronization function: the lock is the class name. Class. It is a class bytecode file object.

/* The ticket seller synchronizes the code block form */class ticket implements runnable {// The interface does not throw an exception, so the run () method can only catch the exception private int num = 100; object OBJ = new object (); Public void run () {While (true) {try {thread. sleep (100); // --- when testing a multi-threaded call, the data num is negative.} catch (interruptedexception e) {system. out. println ("thread error");} synchronized (OBJ) {If (Num> 0) {system. out. println (thread. currentthread (). getname () + "----- sale ----" + num --) ;}}} class ticketdemo {public static void main (string [] ARGs) {ticket T = new ticket (); // --- only one ticket object thread T1 = new thread (t); // thread t2 = new thread (new ticket ()); // thread T3 = new thread (new ticket (); // thread t4 = new thread (new ticket ()); // --- four ticket objects need to be modified using static numthread t2 = new thread (t); thread T3 = new thread (t); thread t4 = new thread (t ); t1.start (); t2.start (); t3.start (); t4.start ();}

Example: the bathroom on the train

Synchronization benefits: Solves the thread security issues.
Disadvantages of synchronization: This reduces the efficiency because synchronization locks are determined by all threads outside of synchronization.
Synchronization premise: there are multiple threads and the same lock is used.

Singleton design mode:

Make the class have only one object (constructor privatize, create the class object in the class and privatize it into static, define the public static method, and call the return object)
Hungry Chinese Style: objects are loaded when the class enters the memory. Thread security does not exist.
Lazy: delays loading objects. The Synchronous Code block is used. The lock is the class name. Class, and a judgment (double-layer judgment) is performed outside the lock ). This prevents the lock from wasting resources.

/* Multi-threaded singlehg design mode * // --- ELE. Me class singlehg {Private Static final singlehg S = new singlehg (); Private singlehg () {} public static singlehg getinstance () {return s ;}// --- lazy class singlelz {Private Static singlelz S = NULL; private singlelz () {} public static singlelz getinstance () {If (S = NULL) S = new singlelz (); Return s ;}}// --- lazy style with synchronization lock, which is frequently used in interviews, generally, the hungry Chinese class single {Private Static Single S = NULL; private single () {} public static/* synchronized */single getinstance () {// --- using the synchronization function will reduce efficiency, and the lock if (S = NULL) synchronized (single. class) {If (S = NULL) S = new single ();} return s ;}}

Deadlock program:

Interrupt (); force the thread's freeze state to get the thread's execution qualification, but it will throw interruptedexception

Inter-thread communication: multiple threads operate on the same resource, but the operations are different;

Consider synchronization issues and add the wait for wake-up mechanism; wait () y ()
Wait (); y (); notifyall (); these methods should be used in the synchronization code to operate on the thread holding the lock.
These methods are defined in the object class, And all objects can be locks. These methods can only wake up or wait for the thread holding the same lock.

Producer and consumer problems:

Multiple producer consumers must use the while () loop to judge the mark;

Class duck {private int ID; duck (int id) {This. id = ID;} public int GETID () {return ID;} public void setid (int id) {This. id = ID ;}@ overridepublic string tostring () {return "duck [ID =" + ID + "]" ;}} class duckbasket {int Index = 0; duck [] ducks = new duck [5]; Public synchronized void push (duck) {While (Index = ducks. length) Try {system. out. println (thread. currentthread (). getname () + ": When the basket is full, the rest will be ~~~~~~~~~! "); This. wait ();} catch (interruptedexception e) {// Catch Block E automatically generated by todo. printstacktrace ();} ducks [Index] = duck; system. out. println (thread. currentthread (). getname () + "produced" + duck); index ++; y ();} public synchronized duck POP () {While (Index = 0) Try {system. out. println (thread. currentthread (). getname () + ": It's empty. It's time to produce roast duck! "); Wait ();} catch (interruptedexception e) {// Catch Block E automatically generated by todo. printstacktrace ();} index --; // print the output using shared data, which should be placed in the synchronization code system. out. println (thread. currentthread (). getname () + "consumed" + ducks [Index]); y (); Return ducks [Index] ;}} class producer implements runnable {duckbasket dB; public producer (duckbasket dB) {super (); this. DB = dB ;}@ overridepublic void run () {for (INT I = 0; I <20; I ++) {duck = new duck (I); dB. push (duck) ;}} class Consumer implements runnable {duckbasket dB; public consumer (duckbasket dB) {super (); this. DB = dB ;}@ overridepublic void run () {for (INT I = 0; I <20; I ++) {dB. pop () ;}} public class producerconsumerdemo {/*** @ Param ARGs */public static void main (string [] ARGs) {duckbasket DB = new duckbasket (); producer pro1 = new producer (db); consumer con1 = new consumer (db); thread T1 = new thread (pro1, "producer ---- 1 "); thread t2 = new thread (con1, "Consumer 1"); thread T3 = new thread (pro1, "producer ---- 2"); thread t4 = new thread (con1, "Consumer 2"); t1.start (); t2.start (); t3.start (); t4.start ();}}

New features, multi-thread upgrade solution, upgrade synchronous synchronized to display lock (Interface ),
Upgrade wait (), Policy (), and policyall () to a condition object, which can be obtained through the lock.
You can only wake up the other party.

Import Java. util. concurrent. locks. condition; import Java. util. concurrent. locks. lock; import Java. util. concurrent. locks. reentrantlock; Class duck {private int ID; duck (int id) {This. id = ID;} public int GETID () {return ID;} public void setid (int id) {This. id = ID ;}@ overridepublic string tostring () {return "duck [ID =" + ID + "]" ;}} class duckbasket {int Index = 0; duck [] ducks = new duck [5]; lock = new R Eentrantlock (); condition prol = lock. newcondition (); condition conl = lock. newcondition (); Public void push (duck) {lock. lock (); try {While (Index = ducks. length) Try {system. out. println (thread. currentthread (). getname () + ": When the basket is full, the rest will be ~~~~~~~~~! "); Prol. await ();} catch (interruptedexception e) {e. printstacktrace ();} ducks [Index] = duck; system. out. println (thread. currentthread (). getname () + "done" + duck); index ++; conl. signal ();} finally {lock. unlock () ;}} public duck POP () {lock. lock (); try {While (Index = 0) Try {system. out. println (thread. currentthread (). getname () + ": It's empty. Make it a roast duck! "); Conl. await ();} catch (interruptedexception e) {e. printstacktrace ();} index --; // print the output using shared data, which should be placed in the synchronization code system. out. println (thread. currentthread (). getname () + "consumed" + ducks [Index]); prol. signal (); Return ducks [Index];} finally {lock. unlock () ;}} class producer implements runnable {duckbasket dB; Public producer (duckbasket dB) {super (); this. DB = dB ;}@ overridepublic void run () {for (INT I = 0; I <20; I ++) {duck = new duck (I); dB. push (duck) ;}} class Consumer implements runnable {duckbasket dB; public consumer (duckbasket dB) {super (); this. DB = dB ;}@ overridepublic void run () {for (INT I = 0; I <20; I ++) {dB. pop () ;}} public class proconlock {/*** @ Param ARGs */public static void main (string [] ARGs) {duckbasket DB = new duckbasket (); producer pro1 = new producer (db); consumer con1 = new consumer (db); thread T1 = new thread (pro1, "producer ---- 1 "); thread t2 = new thread (con1, "Consumer 1"); thread T3 = new thread (pro1, "producer ---- 2"); thread t4 = new thread (con1, "Consumer 2"); t1.start (); t2.start (); t3.start (); t4.start ();}

How to stop a thread?

1. Control the loop. Make a flag so that when the mark changes, stop the loop and end the run () method;
2. If the thread is in the waiting (frozen) State and cannot end the thread, you can use the interrupt () method to forcibly unfreeze the thread and enter the running state. In this way, you can mark the operation and end the thread.

The similarities between wait () and sleep () can both bring threads into the frozen state and throw exceptions.

Differences:
1. Wait () is the object method, and sleep () is the thread method.
2. Wait () must be locked
3. Wait () requires wake-up by Y (). When sleep () expires, the system automatically obtains the CPU execution qualification.

Other methods

Join () method. When thread a executes the join method of thread B, thread a waits until the execution of thread B finishes.

Setdaemon (); daemon. The process ends when the foreground ends.

The tostring () method of the thread class. The return value is [program name, priority, thread group].

Setpriority () sets the priority max_priority min_priority normal_priority setname ()

Yield (); static method: Pause the execution of the current thread

Anonymous internal class creation process-Common. ------- Android training, Java training, and hope to communicate with you! ----------

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.