"JAVA concurrency Programming" Six: runnable and thread to achieve the difference between multithreading (including code) __java

Source: Internet
Author: User
Tags inheritance thread class ticket

Reprint Please indicate the source: http://blog.csdn.net/ns_code/article/details/17161237


There are two ways to implement multithreading in Java: To inherit the thread class and implement the Runnable interface, as long as it is multi-threaded in the development of the program, it is always to realize the runnable interface, because the implementation of the Runnable interface has the following advantages over the inheritance thread class:

1, can avoid the single inheritance of Java because of the limitations caused by the characteristics;

2, enhance the robustness of the program, code can be shared by multiple threads, the code and data is independent;

3. A thread area that is suitable for multiple identical program codes handles the same resource.


The following is an example of a typical ticket-buying process (basically taking this as an example) to illustrate the difference.

The code is implemented first by inheriting the thread class:

Class Mythread extends thread{
	private int ticket = 5;
	public void Run () {for
		(int i=0;i<10;i++)
		{
			if (Ticket > 0) {
				System.out.println ("ticket =" + ticket--)
;

}}} public class threaddemo{public
	static void Main (string[] args) {
		new Mythread (). Start ();
		New Mythread (). Start ();
		New Mythread (). Start ();
	}
}
The results of a certain execution are as follows:


As can be seen from the results, each thread sold a separate 5 tickets, that is, the independent completion of the task of buying tickets, but the actual application, such as the railway station ticketing, need multiple threads to work together to complete the task, in this case, that is, multiple threads to buy 5 tickets together.

The following is a multithreaded program implemented through the implementation of the Runnable interface, with the following code:

Class Mythread implements runnable{
	private int ticket = 5;
	public void Run () {for
		(int i=0;i<10;i++)
		{
			if (Ticket > 0) {
				System.out.println ("ticket =" + ticket--)
;

}}} public class runnabledemo{public
	static void Main (string[] args) {
		Mythread i = new Mythread ();
		New Thread (My). Start ();
		New Thread (My). Start ();
		New Thread (My). Start ();
The results of a certain execution are as follows:


As can be seen from the results, three threads sold a total of 5 tickets, that is, they jointly completed the task of buying tickets, to achieve the sharing of resources.


Add three points for the above code:

1, in the second method (Runnable), the order of the ticket output is not 54321, because the timing of the thread execution is unpredictable, and ticket--is not an atomic operation.

2. In the first method, we have new 3 thread objects, three threads executing the code in each of the three objects, so it is three threads that do the task of selling tickets independently, and in the second method we also have a new 3 thread object, but only one runnable object, 3 thread objects share the code in this Runnable object, so there will be 3 threads working together to complete the results of the ticket sales task. If we new 3 runnable objects and pass them in to 3 thread objects, then 3 threads will independently execute the code in their respective runnable objects, that is 3 threads selling 5 tickets each.

3. In the second method, because 3 thread objects work together to execute the code in a Runnable object, it can cause thread insecurity, such as the possibility that ticket will output 1 if we system.out .... statement preceded by a thread hibernation operation, this situation is likely to occur because, a thread after judging ticket as 1>0, has not had time to subtract 1, another thread has ticket minus 1 to 0, then the next thread will ticket minus 1, then got-1. This requires a synchronization operation (a mutex) to ensure that only one thread at a time executes the action in each for loop. In the first method, there is no need to join a synchronization operation because each thread executes the code in its own thread object, and there is no case where multiple threads are executing the same method together.

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: [email protected] 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.