Two simple examples of Java multi-thread programming

Source: Internet
Author: User

/*** @ Author gao */package gao.org; public class RunnableDemo implements Runnable {@ Overridepublic void run () {// TODO Auto-generated method stubfor (int I = 0; I <10; I ++) {System. out. println ("new thread output:" + I) ;}} public static void main (String [] args) {Runnable runnable = new RunnableDemo (); // create the Runnable interface object Thread thread = new Thread (runnable); // use the object of the Runnable interface to create the Thread class Object thread. start (); // call the start method of the Thread class to start the new Thread for (int I = 0; I <10; I ++) {System. out. println ("main thread output:" + I );}}}
Main thread output: 0 main thread output: 1 main thread output: 2 new thread output: 0 main thread output: 3 new thread output: 1 main thread output: 4 new thread output: 2 main thread output: 5 new thread output: 3 main thread output: 6 new thread output: 4 main thread output: 7 new thread output: 5 main thread output: 8 new thread output: 6 main thread output: 9 new thread output: 7 new thread output: 8 new thread output: 9

Package gao.org; public class ThreadDemo extends Thread {public void run () {for (int I = 0; I <10; I ++) {System. out. println ("new thread output:" + I) ;}} public static void main (String [] args) {ThreadDemo thread = new ThreadDemo (); // create a Thread object. start (); // start the new thread for (int I = 0; I <10; I ++) {System. out. println ("main thread output:" + I );}}}
Main thread output: 0 main thread output: 1 main thread output: 2 main thread output: 3 main thread output: 4 main thread output: 5 main thread output: 6 main thread output: 7 main thread output: 8 main thread output: 9 new thread output: 0 New thread output: 1 new thread output: 2 new thread output: 3 new thread output: 4 new thread output: 5 new thread output: 6 new thread output: 7 new thread output: 8 new thread output: 9



Related Article

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.