Java language basics: Multithreading

Source: Internet
Author: User

1. There are two ways to create and run a thread:

  • Inherit the Thread class and overwrite the run method. The code in run is executed in another thread.

Class mythread extends thread {<br/> mythread () {<br/> // call the following code to start running the thread <br/> Start (); <br/>}</P> <p> @ override <br/> Public void run () {<br/> // The code is executed in the thread <br/> int I = 0; <br/> while (I <20) <br/>{< br/> system. out. println (I); <br/> try {<br/> sleep (100); <br/>} catch (interruptedexception E) {<br/> // todo auto-generated Catch Block <br/> E. printstacktrace (); <br/>}< br/> ++ I; <br/>}</P> <p> public class main {<br/> Public static void main (string [] ARGs) {<br/> mythread = new mythread (); <br/>}< br/> 

  • Implement the runnable interface and pass it to the new Thread class. The run method of the implementation class is executed in another thread.

// Implement the runnable interface <br/> public class main implements runnable {<br/> @ override <br/> Public void run () {<br/> // The code is executed in the thread <br/> int I = 0; <br/> while (I <20) <br/>{< br/> system. out. println (I); <br/> try {<br/> thread. sleep (100); <br/>} catch (interruptedexception e) {<br/> // todo auto-generated Catch Block <br/> E. printstacktrace (); <br/>}< br/> ++ I; <br/>}</P> <p> Public static void main (string [] ARGs) {<br/> main runable = new main (); <br/> New thread (runable ). start (); <br/>}< br/> 

 

2.
The background thread (Daemon) is not an indispensable part of the program. When the program has a non-Background thread, the program will not be terminated. If the non-Background thread ends, at this time, the program can be terminated at any time regardless of whether there are any background threads. To set a thread as a background thread, call thread. setdaemon (true) and create other threads in one background thread. These threads are also automatically set as background threads: Class mythread extends thread {<br/> mythread () {<br/> // set this thread to a background thread <br/> setdaemon (true ); <br/> // call the following code to start running the thread <br/> Start (); <br/>}</P> <p> @ override <br/> Public void run () {<br/> // The code is executed in the thread <br/> int I = 0; <br/> while (I <20) <br/>{< br/> system. out. println (I); <br/> try {<br/> sleep (100); <br/>} catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}< br/> ++ I; <br/>}</P> <p> public class main {<br/> Public static void main (string [] ARGs) {<br/> mythread = new mythread (); <br/> // mythread. run stops the program before execution. <br/>}< br/> // The program stops when it is printed as 0, the preceding example program is printed until 19. <br/>3.
In the above example, how does one let the main thread end when the background thread ends? The answer is to call the jion () method of the background thread. You can pass in a timeout parameter. If this parameter is not set, the result is returned until the background thread ends: Class mythread extends thread {<br/> mythread () {<br/> // set this thread to a background thread <br/> setdaemon (true ); <br/> // call the following code to start running the thread <br/> Start (); <br/>}</P> <p> @ override <br/> Public void run () {<br/> // The code is executed in the thread <br/> int I = 0; <br/> while (I <20) <br/>{< br/> system. out. println (I); <br/> try {<br/> sleep (100); <br/>} catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}< br/> ++ I; <br/>}</P> <p> public class main {<br/> Public static void main (string [] ARGs) {<br/> mythread = new mythread (); <br/> try {<br/> // wait until the background thread ends <br/> mythread. join (); <br/>}catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}< br/>}4.
When two threads read and write the same copy of data at the same time, resource conflicts may occur. In this case, a synchronization mechanism must be provided in addition to the parallel mechanism, the read and write operations on the data can be performed in an orderly manner. Java is very simple to handle this, that is, using the synchronized keyword:
  • Add synchronized before a common method to convert the method into a synchronous method. First, let's look at the following example. When the main thread and working thread call synproc at the same time, whoever calls it first gets a lock, the other one can only wait, so that the method can be called in a multi-threaded environment in order:

Class mythread extends thread {<br/> mythread () {<br/> Start (); <br/>}</P> <p> @ override <br/> Public void run () {<br/> synproc (); <br/>}</P> <p> synchronized public void synproc () {<br/> int COUNT = 0; <br/> while (count ++ <10) {<br/> try {<br/> sleep (100); <br/> system. out. println ("synproc:" + count); <br/>} catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}</P> <p> public class main {<br/> Public static void main (string [] ARGs) {<br/> mythread thread = new mythread (); <br/> thread. synproc (); <br/>}< br/> // The output result is: <br/> synproc: 1 <br/> synproc: 2 <br/> synproc: 3 <br/> synproc: 4 <br/> synproc: 5 <br/> synproc: 6 <br/> synproc: 7 <br/> synproc: 8 <br/> synproc: 9 <br/> synproc: 10 <br/> synproc: 1 <br/> synproc: 2 <br/> synproc: 3 <br/> synproc: 4 <br/> synproc: 5 <br/> synproc: 6 <br/> synproc: 7 <br/> synproc: 8 <br/> synproc: 9 <br/> synproc: 10 <br/> 

  • In fact, the synchronized method is at the object level. Each object has a lock. When any of its synchronization methods is called, the object lock is obtained. When the object lock is obtained, other synchronous methods cannot be called at the same time. They can only be called after the method is executed. The following code clearly describes this point:

Class mythread extends thread {<br/> mythread () {<br/> Start (); <br/>}</P> <p> @ override <br/> Public void run () {<br/> synproc (); <br/>}</P> <p> synchronized public void synproc () {<br/> int COUNT = 0; <br/> while (count ++ <10) {<br/> try {<br/> sleep (100); <br/> system. out. println ("synproc:" + count); <br/>} catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}</P> <p> synchronized public void synproc2 () {<br/> int COUNT = 0; <br/> while (count ++ <10) {<br/> try {<br/> sleep (100 ); <br/> system. out. println ("synproc2:" + count); <br/>} catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}</P> <p> public class main {<br/> Public static void main (string [] ARGs) {<br/> mythread thread = new mythread (); <br/> thread. synproc2 (); <br/>}< br/> // output <br/> synproc2: 1 <br/> synproc2: 2 <br/> synproc2: 3 <br/> synproc2: 4 <br/> synproc2: 5 <br/> synproc2: 6 <br/> synproc2: 7 <br/> synproc2: 8 <br/> synproc2: 9 <br/> synproc2: 10 <br/> synproc: 1 <br/> synproc: 2 <br/> synproc: 3 <br/> synproc: 4 <br/> synproc: 5 <br/> synproc: 6 <br/> synproc: 7 <br/> synproc: 8 <br/> synproc: 9 <br/> synproc: 10 

  • Synchronized can be added to the front of the static method, and each class also has a lock. Calling the synchronous static method is to obtain the class-Level Lock, which makes all synchronized static methods in the class orderly, that is to say, only one static synchronous method is called, and other static synchronous methods have to wait until it ends before being called.
  • Synchronized can also be added to a method, called a synchronization block, such as synchronized (OBJ ){...} this syntax is actually used to obtain the lock of the OBJ object, so the OBJ synchronization method will also be affected, that is, when the OBJ synchronization block is executed, the OBJ synchronization method can be called only after the synchronization block is executed:

Class mythread extends thread {<br/> mythread () {<br/> Start (); <br/>}</P> <p> @ override <br/> Public void run () {<br/> synproc (); <br/>}</P> <p> Public void synproc () {<br/> int COUNT = 0; <br/> synchronized (this) {<br/> do {<br/> try {<br/> sleep (50); <br/>} catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}< br/> system. out. println ("synproc:" + count); <br/>}while (count ++ <3 ); <br/>}</P> <p> synchronized public void synproc2 () {<br/> int COUNT = 0; <br/> do {<br/> try {<br/> sleep (50); <br/>} catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}< br/> system. out. println ("synproc2:" + count); <br/>}while (count ++ <3 ); <br/>}</P> <p> public class main {<br/> Public static void main (string [] ARGs) {<br/> mythread thread = new mythread (); <br/> thread. synproc2 (); <br/>}< br/> // output: <br/> synproc2: 0 <br/> synproc2: 1 <br/> synproc2: 2 <br/> synproc2: 3 <br/> synproc: 0 <br/> synproc: 1 <br/> synproc: 2 <br/> synproc: 3 

5. The waiting and notification between threads are implemented through Wait, y, and notifyall.

  • All three methods must be executed in the synchronization block of the object. Otherwise, an illegalmonitorstateexception occurs at runtime.
  • When thread a calls obj. Wait (), A is suspended until another thread B calls obj. Every y () or obj. Every yall.
  • If only one thread calls obj. wait (), the other thread only needs to call obj. Y (); but if multiple threads call obj. wait (), the other thread must call obj. yyall () can wake up all threads.

The following code demonstrates the collaboration process between a writer and multiple readers:

Class Writer extends thread {<br/> private char CHR; </P> <p> @ override <br/> Public void run () {<br/> for (char c = 'a'; C <= 'Z'; ++ c) {<br/> CHR = C; <br/> // notify reader to read <br/> synchronized (this) {<br/> policyall (); <br/>}< br/> // write again later <br/> try {<br/> sleep (100); <br/>} catch (interruptedexception E) {<br/> E. printstacktrace (); <br/>}</P> <p> Public char getchar () {<br/> return CHR; <br/>}</P> <p> class reader extends thread {<br/> private writer; </P> <p> reader (writer) {<br/> This. writer = writer; <br/> Start (); <br/>}</P> <p> @ override <br/> Public void run () {<br/> while (true) {<br/> // wait for writer to write <br/> synchronized (writer) {<br/> try {<br/> // here the reader thread will be suspended <br/> writer. wait (); <br/>}catch (interruptedexception e) {<br/> E. printstacktrace (); <br/>}< br/> // read the content written by writer <br/> char CHR = writer. getchar (); <br/> system. out. print (CHR + ""); <br/> // It ends when Z is read. <br/> If (CHR = 'Z') {<br/> system. out. println (); <br/> break; <br/>}</P> <p> public class main {<br/> Public static void main (string [] ARGs) {<br/> writer = new writer (); <br/> reader reader1 = new reader (writer); <br/> reader reader2 = new reader (writer ); <br/> // start <br/> writer. start (); <br/>}< br/> // The final output is: <br/> A a B c d e f g h I j k l m n o p Q r s t u v v w x y z <br/> Z 

 

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.