Java multithreading: Implementation Method

Source: Internet
Author: User

In Java, multithreading can be implemented in two ways:
Extended java. Lang. Thread class
Implement the java. Lang. runnable interface
Method 1

 
/*** @ Description: inherits the Thread class and implements multiple threads. * @ author Snoopy * @ blog http://blog.csdn.net/huang_xw */package basic. a_start; import Org. apache. log4j. logger; public class testthread extends thread {Private Static logger = logger. getlogger (testthread. class); public static void main (string [] ARGs) {testthread test = new testthread (); logger. debug ("Start the thread in the main thread! "); Test. Start ();} public void run () {logger. debug (" Run in thread! ");}}

Method 2

/*** @ Description: multiple threads used to test the runnable class. Program * @ Author Snoopy * @ blog http://blog.csdn.net/huang_xw */package basic. a_start; import Org. apache. log4j. logger; public class testrunnable {Private Static logger = logger. getlogger (testrunnable. class); public static void main (string [] ARGs) {// 1. process tasks Code Move to the run method of the class that implements the runnable interface. // 2. create an object for the task class // 3. create a thread object by runnable // 4. start thread imprunnable R1 = new imprunnable (); imprunnable r2 = new imprunnable (); // There are two ways to name a thread // 1. virtual Machine name 2. thread T1 = new thread (R1, "thread 1"); thread t2 = new thread (R2, "thread 2"); t1.start (); t2.start () ;}} class imprunnable implements runnable {Private Static logger = logger. getlogger (imprunnable. class); // This thread completes when the thread's target run () method ends. Public void run () {for (INT I = 0; I <10; I ++) {// For loop to simulate a time-consuming operation for (long K = 0; k <100000000; k ++); // The method for getting the object of the current thread is: thread. currentthread () Logger. debug (thread. currentthread (). getname () + "run" + ":" + I + "times ");}}}

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.