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 ");}}}