Way java_6 threads created

First, create a thread method

1. Thread class inheritance

Implemented steps of:
(1) create a Thread class inheritance to subclasses
(2) rewriting RUN Thread class () method [manipulation statements threads executing run ()] in
creating an object subclass of the Thread class (3)
(4) this object calls start () method [② ① run method to start the thread that called the current thread object]
Code

//(1)创建一个继承于Thread类的子类
class MyThread1 extends Thread{
    public MyThread1(String name){
        super(name);
    }
        //(2)重写Thread类的run()方法
    @Override
    public void run() {
        System.out.println("第一种创建线程");
        }
    }
}
public class ThreadTest{
    public static void main(String[] args) {
        //(3)创建Thread类的子类的对象
        MyThread1 t1=new MyThread1();
        //(4)通过此对象调用start()方法
        t1.start();
        }
}

2. implement Runnable

Implementation steps
(1) to create a class that implements Runnable interface
(2) to implement the abstract method implementation class in RUN Runnable ()
(3) create an object implementation class
(4) object passed as an argument to this class Thread constructor Create Thread class objects
[Source Thread constructor: public Thread (Runnable target)]
(5) the object by calling the Thread class start ()
Code

//1.创建一个实现了Runnable接口的类
class MyThread2 implements Runnable{
    @Override
    //2.实现类去实现Runnable中的抽象方法run()
    public void run() {
        System.out.println("第二种创建线程:实现Runnable接口");
            }
     }
         public class ThreadTest1 {
    public static void main(String[] args) {
        //3.创建实现类的对象
        MyThread2 m=new MyThread2();
        // 4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
        Thread thread = new Thread(m);
        // 5.通过Thread类的对象调用start()
         thread.start();

Second, explain

Role in front of said start () method:
(1) start a thread
(2) the current thread calls the run () method
then the question arises: Why method uses the Runnable interface to create threads, the Thread class is obviously object calls the start (), Why would ultimately achieve Runnable interface class run () method is executed, rather than run Thread class () method is executed?
The reason for another day, go to class

Guess you like

Origin blog.51cto.com/14234228/2455946