There are two ways to create Java threads __java

Source: Internet
Author: User

There are usually two ways to create equations in Java, one of which is to inherit Thread "class Mythread extends thread{override Run method}" or create Anonymous inner class "new Thread () {Overwrite Run method}". The other is to pass class "class Myrunnable implements runnable{} that implements the Runnable interface to the thread's constructor and then new Thread (New Myrunnable ())" or

New Thread (New Runnable () {Implementing the Run Method}), which creates an anonymous inner class that implements the Runnable interface. Note that we override the Run method when inheriting the parent class, because the thread class is found inside the thread code provided by the JDK, and if the interface runnable is set, the Run method that implements the instance object of the Runnable interface class is invoked. If you don't do anything without setting up runnable, then we can inherit thread to override its run method to achieve the job we want. But the recommended second way is to pass the class that implements the Runnable interface, because it is more in line with object-oriented thinking, and more in line with the idea that JDK has provided to us, the so-called object-oriented method of thinking that we look at threads as a kind of thing, And the thread's specific thing should be encapsulated in another object.

Some of the related source code in the thread class:

    /* What'll be run. *
    private Runnable target;

    Public Thread (Runnable target) {
        init (null, Target, "thread-" + nextthreadnum (), 0);
    }

Thread is also a implements runnable
    @Override public
    void Run () {
        if (target!= null) {
            target.run ();
        }
    }


Post two code that uses anonymous inner classes:

Methods for creating anonymous inner classes in method one:

		Thread thread = new Thread () {
			@Override public
			void Run () {while
				(true) {
					try {
						thread.sleep (500); c6/>} catch (Interruptedexception e) {
						e.printstacktrace ();
					}
					System.out.println ("1:" +thread.currentthread (). GetName () + "---id=" +this.getid ());}}
		;
		Thread.Start ();

Method two passes a way to implement an anonymous inner class that implements the Runnable interface:

		New Thread (New Runnable () {
			@Override public
			void Run () {
				
			}
		}). Start ();
Here's a simple and easy to learn the concepts and usage scenarios for anonymous inner classes:

1. An anonymous inner class is an inner class without a name. There is only one instance of an anonymous class. An anonymous inner class is equivalent to declaring a subclass, except that the subclass has no name. And it can only exist within the class or inside the method, so it is called anonymous inner class. This is a mechanism designed by Java to facilitate programmers to write programs. Because sometimes some internal classes just need to create an object on it, it will not be used in the future, the use of anonymous inner class is more appropriate, but also eliminates the trouble of naming it.

2. It is appropriate to use an anonymous inner class if some of the following conditions are true:
• Only one instance of the class is used.
• Classes are used immediately after definition.
• Class very Small (sun recommended below 4 lines of code)
• Naming a class doesn't make your code easier to understand.
When using anonymous inner classes, keep in mind the following principles:
• Anonymous inner classes cannot have construction methods.
• Anonymous inner classes cannot define any static members, methods, and classes.
• Anonymous inner class cannot be public,protected,private,static.
• Only one instance of an anonymous inner class can be created.
• An anonymous inner class must be behind new, with its implied implementation of an interface or implementation of a class.
• Because the anonymous inner class is a local inner class, all restrictions on the local inner class are in effect.

Consider a question: if you take new Thread (new Runnable () {Implement Run method}) {Overwrite the Run method}.start () where it will be executed. The answer is to execute the overridden run method, because the new runnable is equivalent to passing runnable to the parent class, and the overridden run method is to overwrite the anonymous inner class (the subclass of thread) and invalidate the Run () method of the parent class.


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.