Multithreading in Java)

Source: Internet
Author: User

Simple implementation process of multithreading:

(1) Move the task processing code to the run method of the class implementing the runnable interface. This interface is very simple and has only one method:

Public interface runnable

{

Void run ();

}

Implement such a class:

Class myrunnable implements runnable

{

Public void run ()

{

 

}

}

Create an object for this class:

Runnable r = new myrunnable ();

Then, runnable creates a thread object:

Thread t = new thread (R );

Startup thread:

T. Start ();

(2) There is also a convenient method for code writing to create a subclass of the thread class.

Class mythread extends thread

{

Public void run ()

{

 

}

}

Create an object for this class and call the start method.

Note: if there are few threads, you can use the above method. If there are too many threads, we recommend using the thread pool.

2009.5.23

Thread interruption:

In Java, threads cannot be forcibly interrupted. On the contrary, each thread has an interruption status flag. When the external code wants to terminate a thread, it can call the interrupt method of the thread. After the call, the thread's interrupt status flag is automatically set to true (isinterrupted () = true). If the thread has a judgment on the interrupt status flag, you can decide whether to respond to the interrupt request.

What does the above mean? That is to say, the thread will determine whether someone wants to interrupt itself. If someone wants to interrupt, you can decide whether the thread is actually interrupted. If this thread is very important, the execution can be continued without interrupting the request.

Therefore, the typical thread code is as follows:

While (! Thread. currentthread (). isinterrupted ())

{

 

}

Of course, this code is not all, because there is another situation that is not handled, that is, what if the current thread is sleep or wait?

When the interrupt method of a thread is called and the thread is sleep, an interruptedexception exception occurs in the thread to interrupt the thread sleep or wait. In fact, we found that during sleep, Java requires a try to catch this exception. A typical sleep code is as follows:

Try {

Thread. Sleep (1000 );

} Catch (interruptedexception e ){

// Todo auto-generated Catch Block

E. printstacktrace ();

}

At this time, the Code is being blocked by thread. Sleep (1000). It is suddenly caught by interrupt.

Therefore, there are two typical code structures for a thread. The first one is not always sleep:

Public void run ()

{

Try

{

......

While (! Thread. currentthread (). isinterrupted ())

{

 

}

}

Catch (interruptedexception E)

{

// When sleep or wait is interrupted, it will jump here

}

Finally

{

// Clean up the site

}

}

The above Code does not often use sleep, so you should regularly check the interruption status to handle the interruption.

If sleep is required for each loop, the isinterrupted check is not required. Because, when the Code sleep or wait is interrupted, it will directly go into Exception Handling. If it is not sleep or wait, when sleep or wait is called, sleep or wait detects that the interrupt status flag is true and directly throws an exception. The Code is as follows:

Public void run ()

{

Try

{

......

While (expression)

{

 

Thread. Sleep (Delay );

}

}

Catch (interruptedexception E)

{

// Interrupted

}

Finally

{

// Clean up the site

}

}

Note: When sleep throws an exception, the interruption state is cleared.

Note: There are two very similar methods: interrupted and isinterrupted. Interrupted is a static method that checks whether the current thread has been interrupted. Besides, calling the interrupted method will clear the thread interruption status. On the other hand, the isinterrupted method is an instance method that can be used to check whether the thread is interrupted. Call it without changing the interrupt status value.

If thread a wants to wait until thread B finishes its execution, it can do this:

B. Join ();

Call the blocking method of B to block a until B returns the result.

In a lot of released code, we often see that the interruptedexception exception is blocked at a very low level, like this:

Void mysubtask ()

{

......

Try {sleep (Delay );}

Catch (interruptedexception e) {}// the processing code should not be ignored here

......

}

Ignore error handling is very undesirable. If you do not change this structure, there are two reasonable options:

First, add thread. currentthread (). Interrupt () to catch to set the interrupt status. This ensures that the interrupt status is not damaged, so that the caller can test it.

Second, a better choice is that the method marked out will throw an interruptedexception exception, and the try statement block will not be used to capture the exception. Then, the caller (or, the final run method) can capture this exception.

Void mysubtask () throws interruptedexception

{

......

Sleep (Delay );

......

}

Thread status:

The thread has four states:

New: A New thread is not running yet. You have to do some work before running it.

Runnable: There are two statuses: running and running, but not running.

Blocked: the thread cannot be moved.

Dead (death): there are two types: natural death (run execution completed) and sudden death (run exception but not handled.

Note: you cannot determine whether a live thread is runable or blocked, or whether a runable thread is running. In addition, the dead threads and non-runable threads cannot be distinguished.

Thread Synchronization:

There are two typical Synchronization Methods in Java: block synchronization and method synchronization, both of which use the synchronized keyword.

Synchronization method:

If the synchronized keyword is added to a method in a class, it becomes a synchronous method. When one thread calls this synchronous method, the other thread callsAll Synchronization Methods of this classWill be blocked until the previous thread has finished calling.

The typical code is as follows:

Public synchronized void method ()

{

 

}

Synchronization block:

Like vs, lock a reference type object:

Synchronized (s)

{

......

S. Add ();

......

}

Wait and policy are the object method, not the thread method. Wait can temporarily discard the current lock thread and give other blocked threads a chance to execute the lock. If wait exists, append policy or policyall at the end of the Code to wake up the thread that gives up the lock.

Wait is generally used for collaboration between two or more threads. For example, threads a and B operate C together. Thread a has been processing C for a long time, but thread B has not started yet. If the difference between the two operations is not very large, a can first wait, so that B has the opportunity to deal with C.

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.