Java programming-sun Xin Java has no difficulties lesson7 Multithreading

Source: Internet
Author: User
Java program design -- Sun Xin Java has no difficulties lesson7 Multithreading

1. Programs, processes, and threads
Program: A program is a collection of computer commands. It is stored on a disk as a file.
Process: an execution activity of a program in its own address space. A process is a unit of resource application, scheduling, and independent operation. Therefore, it uses running resources in the system. A program cannot apply for system resources or be scheduled by the system, it cannot be used as an independent operating unit. Therefore, it does not occupy system running resources.

Thread: a single continuous control process in a process. A process can have multiple threads. A thread is also called a lightweight process. It has independent execution control like a process and is scheduled by the operating system. The difference is that the thread does not have independent storage space, instead, it shares a storage space with other threads in the process, which makes the communication between threads much simpler than the process.

2. Java multi-thread implementation
JAVA supports multi-threaded programming at the language level.
Two methods for implementing multi-threaded programs:
A. inherit from Thread class
B. Implement the runnable interface
(1) Implementation Method 1 inherited from the Thread class
The test code is as follows:

Class mythread extends thread {mythread (string name) {super (name);} public void run () {While (true) {system. out. println (getname (); yield (); // pause thread running} class multithread {public static void main (string [] ARGs) {// derived from the Thread class mythread Mt = new mythread ("thread1"); // Mt. setdaemon (true); // mark as the background thread Mt. setpriority (thread. max_priority); // sets the highest priority Mt. start (); // the startup thread int Index = 0; // when only the background thread is running, the Java Virtual Machine will exit while (true) {If (index ++ = 100) break; // exit the system using the main method. out. println ("Main:" + thread. currentthread (). getname ());}}

(2) Implementation Method 2: implement the runnable interface
The test code is as follows:
// The implemented interface allows the inherited class and the same resource access through the interface

Class mythread implements runnable {int Index = 0; // shared variable public void run () {While (true) {system. out. println (thread. currentthread (). getname () + index ++) ;}} class multithread {public static void main (string [] ARGs) {mythread Mt = new mythread (); New thread (MT ). start (); // transfer the implementation Class Object of the runnable interface new thread (MT ). start (); New thread (MT ). start (); New thread (MT ). start (); While (true) {system. out. println ("Main:" + thread. currentthread (). getname ());}}

As shown in the following figure:


(3) Implementation Method 3. Use internal classes to inherit from thread classes
The test code is as follows:

// Use internal classes to inherit from threadclass mythread {int Index = 0; private class innerthread extends thread {public void run () {While (true) {system. out. println (thread. currentthread (). getname () + index ++) ;}} public thread getthread () {return New innerthread () ;}} class multithread {public static void main (string [] ARGs) {mythread Mt = new mythread (); Mt. getthread (). start (); Mt. getthread (). start (); While (true) {system. out. println ("Main:" + thread. currentthread (). getname ());}}}

3. Thread Synchronization
Two synchronous Methods: Synchronous block and synchronous method
Each object has a monitor or lock.
The synchronization method uses the lock of the object represented by this. The Class Object monitor of the class used for static method synchronization. Each class also has a lock, which is the lock of the Class Object corresponding to this class.
(1) An error occurred when the thread is not synchronized:
The test code is as follows:

Class sellthread implements runnable {int tickets = 1000; object Ob = new object (); Public void run () {While (true) {// No lock if (tickets> 0) {try {thread. sleep (5);} catch (exception e) {system. out. println (E. tostring ();} system. out. println (thread. currentthread (). getname () + "effectickets" + tickets); tickets -- ;}} class ticketssystem {public static void main (string [] ARGs) {sellthread ST = new sellthread (); new thread (ST ). start (); New thread (ST ). start ();}}

// Running result
Thread-0 maid
Thread-1 maid
Thread-0 maid
Thread-1 maid
Thread-0 maid
Thread-1 maid
Thread-0 javastickets5
Thread-1 maid
Thread-0 maid S3
Thread-1 javastickets2
Thread-0 maid
Thread-1 maid
(2) thread synchronization method 1-use synchronization Blocks
The test code is as follows:

Class sellthread implements runnable {int tickets = 1000; object Ob = new object (); Public void run () {While (true) {synchronized (OB) // The synchronization block locks the object {If (tickets> 0) {try {thread. sleep (5);} catch (exception e) {system. out. println (E. tostring ();} system. out. println (thread. currentthread (). getname () + "effectickets" + tickets); tickets -- ;}// unlock the synchronization block after execution} class ticketssystem {public static void main (string [] ARGs) {sellthread ST = new sellthread (); New thread (ST ). start (); New thread (ST ). start ();}}

Synchronization block. The running result is shown in:


(3) thread synchronization method 2 -- Synchronization Method
The test code is as follows:

Class sellthread implements runnable {int tickets = 1000; object Ob = new object (); Public void run () {While (true) {Merge (); // synchronous method} // synchronized keyword defines the synchronous method to lock the monitor of this object public synchronized void Merge () {If (tickets> 0) {try {thread. sleep (10);} catch (exception e) {system. out. println (E. tostring ();} system. out. println (thread. currentthread (). getname () + "effectickets" + tickets); tickets -- ;}// unlock this object} class ticketssystem {public static void main (string [] ARGs) {sellthread ST = new sellthread (); New thread (ST ). start (); New thread (ST ). start ();}}

Shows the synchronization method:


(4) Note that the synchronization method locks this object, while the synchronization block synchronizes a defined object.
The verification code is as follows:

Class sellthread implements runnable {int tickets = 500; // different data may run in different threads. Object OBJ = new object (); Boolean B = false; Public void run () {If (B = false) {While (true) {Merge () ;}} else {While (true) {synchronized (OBJ) // An error occurred while synchronizing the OBJ object. Synchronization of this is correct {try {thread. sleep (10);} catch (exception e) {system. out. println (E. tostring ();} If (tickets> 0) {system. out. println ("OBJ" + thread. currentthread (). getname () + "effectickets" + tickets); tickets -- ;}}}// the synchronization method locks the monitor of this object to public synchronized void Merge () {If (tickets> 0) {try {thread. sleep (10);} catch (exception e) {system. out. println (E. tostring ();} system. out. println ("success" + thread. currentthread (). getname () + "effectickets" + tickets); tickets -- ;}// unlock this object}

An error occurs when the restore method is called and an object is synchronized. The error result is shown in:


When one calls the merge method and the other uses this object for synchronization, the result is correct, as shown in:


4. Thread deadlock
Deadlock test code:

// Test the deadlock class sellthread implements runnable {int tickets = 500; object OBJ = new object (); Boolean B = false; Public void run () {If (B) {While (true) synchronized ();} else {While (true) {// synchronize OBJ objects first and then synchronize this object synchronized (OBJ) {try {thread. sleep (10);} catch (exception e) {system. out. println (E. tostring ();} synchronized (this) {If (tickets> 0) {system. out. println ("deadlock" + thread. currentthread (). getname () + "effectickets" + tickets); tickets -- ;}}}}// synchronize this object first and then the OBJ object public synchronized void Merge () {synchronized (OBJ) {try {thread. sleep (10);} catch (exception e) {system. out. println (E. tostring ();} If (tickets> 0) {system. out. println ("deadlock" + thread. currentthread (). getname () + "effectickets" + tickets); tickets -- ;}}// unlock this object} class ticketssystem {public static void main (string [] ARGs) {sellthread ST = new sellthread (); New thread (ST ). start (); try {thread. sleep (10);} catch (exception e) {system. out. println (E. tostring ();} St. B = true; new thread (ST ). start ();}}

// The running result is as follows:
DeadLockThread-0 effectickets500
5. Wait, policy, and policyall
In addition to a lock, each object also has a wait set. when an object is created, its waiting queue is empty.

We should call the wait method of this object after the current thread locks the object lock.

When the notify method of the object is called, an arbitrary thread is deleted from the waiting queue of the object, and the thread becomes a runable thread again. When the notifyall method of the object is called, all waiting threads will be deleted from the waiting queue of the object, and these threads will become runable threads.

Wait and consumer y are mainly used in the relation of producer-consumer.
(1) The Y and wait methods must be executed in the synchronization block. Otherwise, an error occurs. The error message is as follows:
Exception in thread "thread-0" exception in thread "thread-1" Java. Lang. illegalm
Onitorstateexception
At java. Lang. Object. Y (native method)
At queue. Get (test. Java: 81)
At consumer. Run (test. Java: 40)
Java. Lang. illegalmonitorstateexception
At java. Lang. Object. Y (native method)
At queue. Put (test. Java: 55)
At producer. Run (test. Java: 23)
Note that exceptions must be caught in the wait method.
(2) consumer and producer synchronization Simulation
The test code is as follows:

Class test {public static void main (string [] ARGs) {queue q = new Queue (); producer P = new producer (Q); consumer c = new consumer (Q ); p. start (); C. start () ;}} class producer extends thread {queue Q; Producer (queue q) {This. Q = Q;} public void run () {for (INT I = 0; I <10; I ++) {q. put (I); system. out. println ("producer put" + I) ;}} class Consumer extends thread {queue Q; Consumer (queue q) {This. Q = Q;} public Void run () {While (true) {system. out. println ("consumer get" + q. get () ;}} class queue {int value =-1; Boolean bfull = false; // note that when synchronizing block wait and ipvy, public synchronized void put (int I) must be set for the queue of the same object. {// if it is null, data is placed if (! Bfull) {value = I; bfull = true; y (); // notify the waiting consumer} Try {Wait ();} catch (exception e) {system. out. println (E. tostring () ;}} public synchronized int get () {// If (! Bfull) {try {Wait ();} catch (exception e) {system. out. println (E. tostring () ;}} bfull = false; y (); // notification wait producer return value ;}}

// Running result (I don't know why I didn't print the producer first)
Consumer get 0
Producer put 0
Consumer get 1
Producer put 1
Consumer get 2
Producer put 2
Consumer get 3
Producer put 3
Consumer get 4
Producer put 4
Consumer get 5
Producer put 5
Consumer get 6
Producer put 6
Consumer get 7
Producer put 7
Consumer get 8
Producer put 8
Consumer get 9
Producer put 9
6. Thread termination
Set a flag variable and use the interrupt () method.
The test code is as follows:

Class testthread {public static void main (string [] ARGs) {thread1 T1 = new thread1 (); t1.start (); int Index = 0; while (true) {If (index ++ = 500) {t1.stopthread (); // call the rear stop run flag to true t1.interrupt (); // stop the running thread break;} system. out. println (thread. currentthread (). getname ();} system. out. println ("main exit! ") ;}} Class thread1 extends thread {private Boolean bstop = false; Public synchronized void run () {While (! Bstop) {try {Wait (); // It cannot be compared. bstop cannot exit.} catch (interruptedexception e) {// combined with a flag, the flag is determined when the interrupt function is executed, exit the program if (bstop) return; E. printstacktrace ();} system. out. println (getname () ;}} public void stopthread () {bstop = true; // set the stop flag to true }}

// The running result is as follows:
Main
Main
Main
Main
Main
Main
Main
Main
Main
Main exit!
Press any key to continue...

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.