Analysis of the usage of runnable in Java

Source: Internet
Author: User

1, class structure, first there are two classes, one is the test class main, one is the thread class Mythread.

2, MyThread

Package Com.test.thread;import Java.lang.management.threadinfo;public class MyThread implements Runnable {String name= Null MyThread (String name) {this.name=name;} @Overridepublic void Run () {//TODO auto-generated method Stubwhile (True) {System.out.println (name+ ": Output result ...");}}

Main

Package Com.test.thread;public class Main {/** * @param args */public static void Main (string[] args) {//TODO Auto-genera Ted Method Stubmythread mya=new MyThread ("Thread A"); Thread Testa=new thread (mya); Testa.start (); MyThread myb=new MyThread ("thread B"); Thread testb=new thread (MYB); Testb.start ();}}


3. Output results



4. Advanced version

With the above is not good to explain the problem, because the running speed is relatively fast, do not see the two alternate running, if the thread in the process of sleep function, let the thread run for a period of time to hibernate, and then re-restore will be more intuitive, change the code as follows.

Package Com.test.thread;import Java.lang.management.threadinfo;public class MyThread implements Runnable {String name= Null MyThread (String name) {this.name=name;} @Overridepublic void Run () {//TODO auto-generated method Stubwhile (True) {try {thread.sleep ()} catch ( Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println (name+ ": Output result ...");}}

5. Operation Result


Analysis of the usage of runnable in Java

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.