create thread

Create a thread:

inherit the Thread class and override the run() method;

implement the Runnable interface and implement the run() method;

public class TestThread extends Thread{

    public void run(){
        boolean flag= true;
        System.out.println(getName()+"started");
        int count = 0;
        while(flag){
            System.out.println(getName()+"executed"+(++count));
            if(count %10 == 0){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
            }
        }
        System.out.println(getName()+"End");
    }

    public static void main(String[] args){
        Thread threadB = new TestThread();
        Thread threadA = new Thread(new TestThread(),"军队");
        Thread threadC = new Thread(new TestThread2(),"将军");
        threadB.setName("Peasant Uprising");
        threadA.start();
        threadB.start();
        threadC.start();
    }
}

class TestThread2 implements Runnable{
    @Override
    public void run() {
        boolean flag= true;
        System.out.println(Thread.currentThread().getName()+"开始了");
        int count = 0;
        while(flag){
            System.out.println(Thread.currentThread().getName()+"执行了"+(++count));
            if(count %10 == 0){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
            }
        }
        System.out.println(Thread.currentThread().getName()+"结束了");
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326204110&siteId=291194637