Java core programming-thread threading Development Method (II)

Source: Internet
Author: User
Tags thread class

1. Inheriting the thread class

The thread class is a concrete class, not an abstract class.

 PackageSe.thread;Importjava.util.Date; Public classThreadTestextendsThread { Public intTime ;  PublicString name; ThreadTest (inttime,string name) {         This. name=name;  This. time=Time ; }     Public voidrun () { while(true){            Try{System.out.println ("User" + This. name+ "is resting, time:" +NewDate ()); Thread.Sleep ( This. Time); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }     Public Static voidMain (string[] args) {threadtest threadTest1=NewThreadTest, "Jack");        Threadtest1.start (); ThreadTest ThreadTest2=NewThreadTest ("Lolo");    Threadtest2.start (); }}

2. Implement the Runable interface

 PackageSe.thread;Importjava.util.Date; Public classTreadTest2ImplementsRunnable { Public intTime ;  PublicString name;  PublicTreadTest2 (inttime,string name) {         This. name=name;  This. time=Time ; } @Override Public voidrun () { while(true){            Try{System.out.println ("User" + This. name+ "is resting, time:" +NewDate ()); Thread.Sleep ( This. Time); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }     Public Static voidMain (string[] args) {TreadTest2 threadTest2=NewTREADTEST2 (3000, "004"); TreadTest2 treadTest22=NewTreadTest2 (2000, "125"); NewThread (ThreadTest2). Start (); NewThread (treadTest22). Start (); }}

3. Select the thread class or the Runable interface?

1. If you just want to rewrite the runable interface instead of overriding the thread other methods, use the Runable interface.

2. If a subclass inherits other non-thread classes, it can only implement the override of run () by implementing the Runable interface.

Java core programming-thread threading Development Method (II)

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.