Java Multi-thread Runnable VS thread and resource sharing issues

Source: Internet
Author: User

For Java multithreaded programming in the implements Runnable and extends Thread, some students may be more puzzled, what is the difference between them and contact? Do they have a different choice? which one should be chosen in practice?

Even a lot of blog posts online baseless assertion a lot of fallacies, that today's into the Science column will take you one by one to uncover the answer.

1. Difference:

In fact, this is mainly around the interface and abstract class differences and some design principles.

1.1 inheritance Option:

The limitation with "extends thread" approach is so if you extend thread, you can not extend anything else.  Java does not support multiple inheritance. In reality, the need thread class behavior, the because in order to use a thread you need to instantiate one anyway. On the other hand, implementing the Runnable interface gives your the choice to extend any class I like, but still defin E behavior that would be the run by separate thread.

1.2 reusability :

In "Implements Runnable", we is creating a different Runnable class for a specific behavior job (if the work you want t o be do is job). It gives us the freedom to reuse the specific behavior job whenever required. "Extends Thread" contains both thread and job specific behavior code. Hence once thread completes execution, it can not be restart again.

1.3 Object oriented Design:

Implementing Runnable should be preferred. It does not specializing or modifying the thread behavior. You is giving thread something to run. We conclude that composition is the better. Composition means, objects A and B satisfies has-a relationship. "Extends Thread" is a good Object oriented practice.

1.4 loosely-coupled :

"Implements Runnable" makes the code loosely-coupled and easier to read. Because the code is split into the classes. Thread class for the thread specific code and your Runnable implementation class for your job, that should is run by a thre Ad code. "Extends Thread" makes the code tightly coupled. Single class contains the thread code as well as the job, the needs to is done by the thread.

1.5 Functions overhead :

"Extends Thread" means inheriting all the functions of the Thread class which we could do not need. Job can be do easily by Runnable without the Thread class functions overhead.

At this point, the individual is recommended priority choice implements Runnable.

2. Contact:2.1 Actually the thread class is also a subclass of the Runnable interface
public class Thread extends Object implements Runnable
2.2 Startup threads are all start () methods

Tracing the definition of the start () method in thread, you can see that this method uses the private native void Start0 (), where the native keyword means that the underlying function of the operating system can be called, which is called JNI technology (Java native Interface).

However, there is no start () method in a subclass defined with runnable, only in the thread class. At this point the thread class is observed, and there is a constructor: public Thread (Runnable Targer), which accepts the subclass instance of Runnable, which means that the thread class can be used to start the multithreading of the Runnable implementation.

2.3 A Barthelemy theory of network transmission: The use of runnable can realize the sharing of resources, and Thread can not

There are examples of classmates like this, reference: http://developer.51cto.com/art/201203/321042.htm:

package tmp;class mythread extends thread {private int ticket =  10;private string name;public mythread (String name)  {this.name = name;} Public void run ()  {for  (int i = 0; i < 500; i++)  {if  (this.ticket > 0)  {system.out.println (this.name +  "Selling tickets---->"  +  (this.ticket--));}}} Public class threaddemo {public static void main (String[] args)  { Mythread mt1 = new mythread ("one Window"); Mythread mt2 = new mythread ("Window No. second"); Mythread mt3 = new mythread ("Window No. third"); Mt1.start (); Mt2.start (); Mt3.start ();}}   Window Sell ticket---->10//  second window sell ticket---->10//  second window sell ticket---->9//  second window sell ticket---->8//  Third window sell ticket---->10//  Third window sell ticket---->9//  Third window sell ticket---->8 ...

runnable Code:

package tmp;class mythread1 implements runnable {private int ticket =  10;private string name;public void run ()  {for  (int i = 0;  i < 500; i++)  {if  (this.ticket > 0)  {system.out.println ( Thread.CurrentThread (). GetName ()  +  "sell ticket---->"  +  (this.ticket--));}}} Public class runnabledemo {public static void main (String[] args)  { Mythread1 mt = new mythread1 (); Thread t1 = new thread (mt,  "one Window"); Thread t2 = new thread (mt,  "No. second Window"); Thread t3 = new thread (mt,  "Third Window"); T1.start (); T2.start (); T3.start ();}}   second window sell ticket---->10//  Third window sell ticket---->9//  Third window sell ticket---->7//  One window sell tickets---->9//  Third window sell ticket---->6//  second window sell ticket---->8//  Third window sell ticket---->4//  One window sell ticket---->5//  Third window sell ticket---->2//  window No. Second sell tickets---->3//  A window sell tickets---->1 

From this difference, a classmate came to a conclusion: with Runnable can realize the sharing of resources, and Thread can not, this is one of their main differences ...

In fact, a closer look at the code will know that this is only the difference between the two ways, is not implements Runnable and extends Thread of the difference:

MyThread1 MT = new MyThread1 ();  thread T1 = new Thread (MT, "one Window");  Thread t2 = new Thread (MT, "window number second"); thread t3 = new Thread (MT, "window number third");  thread T1 = new Thread (new MyThread1 (), "one Window");  Thread t2 = new Thread (new MyThread1 (), "window number second"); thread t3 = new Thread (new MyThread1 (), "window number third");

In fact, to "resource sharing", Thread can also do:

private static int ticket = 10;//Third window sell ticket---->10//window sell ticket---->9//No. Second window sell ticket---->9//One window sell ticket---->7//One window sell ticket---- >5//Third window Sell ticket---->8//window sell ticket---->4//second window sell ticket---->6//window sell ticket---->2//Third window sell ticket---->3//second window sell ticket---->1

It is possible to have common ticket=10 through static, but the problem comes, and you will find that window 12th sells the 9th ticket.

3. Problems caused by resource sharing: thread safety problems with multithreading

The above example and the results prove that there is a thread-safe problem to be aware of in multithreaded scenarios:

3.1 Synchronous Run () method
Public synchronized void Run ()
3.2 Synchronizing class objects
Synchronized (Test.class)
3.3 Synchronizing certain static objects
Private static Final Object Countlock = new Object (); synchronized (countlock) {count++;}
3.4 Finally give a complete example, the simulation of online ticketing and inquiry:
Package tmp;import java.io.ioexception;import java.util.concurrent.atomic.atomicinteger;public  class demo implements runnable {string name;//static integer tickets  = 20;private static atomicinteger tickets = new atomicinteger (20); Public demo (String name)  {this.name = name;} Public void run ()  {for  (int i = 1; i <= 20; i++)  {synchronized  (tickets)  {if  (Tickets.get ()  > 0)  {try {thread.sleep (1000);}  catch  (interruptedexception e)  {}system.out.println ("I pick up the ticket"  +  ": "  +  tickets.getanddecrement ()  +  "  ticket. ");//tickets--;try {thread.sleep (1000);}  catch  (interruptedexception e)  {}system.out.println ("========== now query still left"  +  ":   " + tickets.get ()  + "   ticket. ");}}}} Public static void main (String[] args)  throws ioexception {demo demo =  new demo ("Hello"); New thread (Demo). Start (); New thread (Demo). Start (); New thread (Demo) . Start ();}}

To here, this issue into science also want to say goodbye to everyone, in fact, chatting with the feeling are running the problem, multithreading this topic a lot, very complex, need to slowly practice and accumulation, I wish you all have fun.

Refer:

[1] Java thread surface question Top 50

Http://www.importnew.com/12773.html

[2] difference between "implements Runnable" and "extends Thread" in Java

Https://www.linkedin.com/pulse/20140917120728-90925576-difference-between-implements-runnable-and-extends-thread-in-java

[3] difference between Thread vs Runnable interface in Java

Http://javarevisited.blogspot.com/2012/01/difference-thread-vs-runnable-interface.html

[4] 5 difference between "Implements Runnable" and "Extends Thread" in Java

Http://javahungry.blogspot.com/2015/05/implements-runnable-vs-extends-thread-in-java-example.html

[5] Differences between runnable and thread in Java

Http://developer.51cto.com/art/201203/321042.htm

[6] Java inherits the difference between the thread class and the implementation of the Runnable interface

http://mars914.iteye.com/blog/1508429

[7] Multi-threaded resource sharing issues

http://blog.csdn.net/king624498030/article/details/45222425

[8] synchronized and static synchronized differences

http://blog.csdn.net/liovey/article/details/7456096

[9] How to synchronize a static variable among threads running different instances of a class in Java?

http://stackoverflow.com/questions/2120248/ How-to-synchronize-a-static-variable-among-threads-running-different-instances-o

Java Multi-thread Runnable VS thread and resource sharing issues

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.