Java core programming-thread development method (2), java Development Method

Source: Internet
Author: User

Java core programming-thread development method (2), java Development Method

1. inherit the Thread class

The Thread class is a specific class, not an abstract class.

Package se. thread; import java. util. date; public class ThreadTest extends Thread {public int time; public String name; ThreadTest (int time, String name) {this. name = name; this. time = time;} public void run () {while (true) {try {System. out. println ("user" + this. name + "resting, time:" + new Date (); Thread. sleep (this. time);} catch (InterruptedException e) {e. printStackTrace () ;}} public static void main (String [] args) {ThreadTest threadTest1 = new ThreadTest (100, "jack"); threadTest1.start (); threadTest threadTest2 = new ThreadTest (200, "lolo"); threadTest2.start ();}}

2. Implement the Runable Interface

Package se. thread; import java. util. date; public class TreadTest2 implements Runnable {public int time; public String name; public TreadTest2 (int time, String name) {this. name = name; this. time = time ;}@ Override public void run () {while (true) {try {System. out. println ("user" + this. name + "resting, time:" + new Date (); Thread. sleep (this. time);} catch (InterruptedException e) {e. printStackTrace () ;}} public static void main (String [] args) {TreadTest2 threadTest2 = new TreadTest2 (3000, "004"); TreadTest2 treadTest22 = new TreadTest2 (2000, "125"); new Thread (threadTest2 ). start (); new Thread (treadTest22 ). start ();}}

3. Select the Thread class or Runable interface?

1. If you only want to rewrite the Runable interface rather than other methods of Thread, use the Runable interface.

2. If the subclass inherits other non-Thread classes, you can only rewrite run () by 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.