To create a thread that implements the Runnable interface
/* * Create thread mode two: Implement Runnable interface * Step: * 1. Create an implementation class for the Runnable interface * 2. Implement the Run method * 3. Create an instance of the implementation class * 4. Create a thread instance and pass an instance of the implementation class as a parameter * 5. Call S Tart method, starts the thread and runs the Run method * / class Mydemo implements Runnable{@Override Public voidRun () { for(inti =1; I <= -; i++) {System.out.println (Thread.CurrentThread (). GetName () +"*****run*******"+ i); } }} Public class Test03 { Public Static voidMain (string[] args) {//Create an instance of the Runnable interface implementation classMydemo d=NewMydemo ();//create thread to pass in an instance of the implementation classThread t=NewThread (D,"MyThread");//Start thread and Execute Run methodT.start (); Thread Thread=thread.currentthread ();//Get current thread instance for(inti =1; I <= -; i++) {System.out.println (Thread.getname () +"*****hello world*******"+ i); } }}
Multithreading
/* Multithreading * phenomenon: The output may not be output sequentially * cause: Although the output code is executed, the result may not be printed, but the other thread is printing ahead of time */ Public class Test04 { Public Static voidMain (string[] args) {/*mythread1 t1 = new MyThread1 (); MyThread1 t2 = new MyThread1 (); T1.start (); T2.start (); */MyThread2 mt=NewMyThread2 (); Thread t1=NewThread (MT,"Window 1"); Thread t2=NewThread (MT,"Window 2"); T1.start (); T2.start (); }} class MyThread1 extends Thread { //generally do not use static, cause: 1.static initialized at class load 2. Life cycle too long Static intnum = -;//Number of votes@Override Public voidRun () { while(Num >0) {System.out.println (Thread.CurrentThread (). GetName () +"******"+ num--); } }} class MyThread2 implements Runnable { intnum = the; @Override Public voidRun () { while(Num >0) {System.out.println (Thread.CurrentThread (). GetName () +"******"+ num--); } }}
Java Learning Note (38)-Create a thread that implements the Runnable interface