Java Threading Application Thread: The second way to create a thread: implementing the Runnable Interface

Source: Internet
Author: User
Tags ticket

/*

Demand: Sell ticket Small program!


Idea: Implement multiple windows (threads) at the same time ticketing.


Step: 1, define the class implementation runnable interface.

2, overwrite the Run method in the Runnable interface.

3, the thread object is created through the thread class.

4, the subclass object of the Runnable interface is passed into the constructor of the thread class as the actual parameter.

5, call the Start method of the thread class to open the thread and invoke the Run method of the Runnabke interface.

*/

The code is as follows

Class Ticket implements Runnable//extends thread//implementation Runnable interface

{

public int tic = 100;

public void Run ()

{

while (TRUE)//default is True

{

if (tic>0)//If the number of votes is greater than 0 execute the following code.

System.out.println (Thread.CurrentThread (). GetName () + "sole ..." +tic--);//define the thread name and reduce the number of votes.

}

}

}

Class Ticketdemo

{

public static void Main (string[] args)

{

Ticket t = new Ticket ();//define Ticket object.

thread T1 = new Thread (t); The subclass object of the Runnable interface is passed into the constructor of the thread class as an actual parameter.

Thread t2 = new Thread (t);

thread t3 = new Thread (t);

Thread t4= new Thread (t);

T1.start ();

T2.start ();

T3.start ();

T4.start ();

Start 4 threads.

}

}


This article is from the "Flying Scorpion" blog, please be sure to keep this source http://tanglongwei.blog.51cto.com/4411684/1671471

Java Threading Application Thread: The second way to create a thread: implementing the Runnable 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.