Java, there are three main ways to create a thread

First, create a Thread class inheritance Thread class

(1) define a subclass of the Thread class and override the run method of the class, method body that represents the run method of the thread to complete the task. Thus the run () method is called executable.

(2) create an instance of a subclass of Thread, the thread object is created.

(3) the calling thread object's start () method to start the thread.

the extends the Thread class ExtendThread {public 


    // override the run method, method body field run method is executable 
    public void run () { 
        for (int I =. 1; I <=. 5; I ++) { 
            System.out.println (the Thread . .currentThread () getName () + "is running" + i); 
            the above code Thread.currentThread () // method returns the currently executing thread object. GetName () method returns the thread invokes the method name 
        } 
    } 

    public static void main (String [] args) { 
        for (int J = 0; J <. 5; J ++) { 
            IF (J == 2) { 
                new new ExtendThread ( ) .start (); 
                new new ExtendThread () Start ();. 
            } 
        } 
    } 
}

 

Second, the realization

public class ImplementRunnable implements Runnable{


    public void run(){
        for(int i = 1;i <=5;i++){
            System.out.println(Thread.currentThread().getName()+" "+i);
        }
    }


    public static void main(String[] args){
        for(int i = 0;i < 5;i++){
            System.out.println(Thread.currentThread().getName()+" "+i);
            if(i==2){
                ImplementRunnable rtt = new ImplementRunnable();
                new Thread(rtt,"新线程1").start();
                new Thread(rtt,"新线程2").start();
            }
        }
    }
}

 

three'

public class Call implements Callable<Integer> {


    @Override
    public Integer call() throws Exception {
        return 1;
    }
}

  

In fact: Thread class implements the interface Runable

And an interface which defines the run Runable a simple abstract no return value () method

 

Guess you like

Origin www.cnblogs.com/qianjinyan/p/11353768.html