The way to implement multithreading runnable

Source: Internet
Author: User
Tags ticket

Package com.thread.runnable;

/**
* There are two ways to implement multithreading, such as inheriting the thread class and implementing the Runnable interface.
* Which way is better? The way that is implemented because of inheritance.
* Reason: 1. Avoid Java but inheritance limitations
* 2. If multiple threads are working on the same resource, the way to implement the interface is more appropriate
* @author Administrator
*
*/
public class Testrunnable {

public static void Main (string[] args) {
Oddtest odd = new Oddtest ();
Eventtest event = new Eventtest ();
New Thread (Odd, "odd"). Start ();
New Thread (event, "even"). Start ();

Testticket ticket = new Testticket ();
New Thread (Ticket, "window One"). Start ();
New Thread (Ticket, "window two"). Start ();
New Thread (Ticket, "window three"). Start ();

}
}

Class Testticket implements runnable{

int ticket = 100;
@Override
public void Run () {

while (true) {
if (Ticket > 0) {
System.out.println (Thread.CurrentThread (). GetName () + "ticketing:" +ticket-);
}else{
Break
}
}
}

}

Class Oddtest implements runnable{

@Override
public void Run () {
for (int i = 1; i <=; i++) {
if (i% 2 = = 0) {
System.out.println (Thread.CurrentThread (). GetName () + ":" +i);
}
}
}

}
Class Eventtest implements runnable{

@Override
public void Run () {
for (int i = 1; i <=; i++) {
if (i% 2! = 0) {
System.out.println (Thread.CurrentThread (). GetName () + ":" +i);
}
}
}

}

The way to implement multithreading runnable

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.