The second way Java creates threads: implementing the Runable Interface

Source: Internet
Author: User



/*
Requirements: A simple ticket selling procedure
Multiple window Tickets

Second way to create a thread: implementing the Runable Interface


*/
/* Step
1. Define class implementation Runable interface
2. Overwrite the Run method in the Runable interface
Store the code that the thread will run in the Run method

3. Creating thread objects through the thread class
4. Pass the subclass object of the Runable interface as the actual argument to the constructor of the thread class
Why pass the subclass object of the Runable interface to the constructor of thread.
Because the object that the custom run method belongs to is the subclass object of the Runable interface
So to get the thread to specify the object's Run method, you must explicitly define the object that the Run method belongs to.

5. Call the Start method of the thread class to open the thread and invoke the Run method of the Runable interface subclass

What is the difference between an implementation and a way of inheriting? (frequently tested on face test)
Implementation benefits: Avoids the limitations of single inheritance
When defining a thread, it is recommended to use the implementation method

There are two different ways to differentiate:
Inherit thread: Threads code holds the run method of the thread subclass
Implement Runable: The Run method of the subclass of the interface where the thread code exists

*/

Class Ticket implements Runnable//extends Thread
{
private static int tick=100;
public void Run ()
{
while (true)
{
if (tick>0)
{
System.out.println (Thread.CurrentThread (). GetName () + "sale:--" +tick--);
}
}
}
}

Class Ticketdemo
{
public static void Main (String args[])
{
Ticket t=new Ticket ();
Thread t1=new thread (t);
Thread t2=new thread (t);
Thread t3=new thread (t);
Thread t4=new thread (t);

T1.start ();
T2.start ();
T3.start ();
T4.start ();
}
}

The second way Java creates threads: implementing the Runable Interface

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.