多线程 Thread

第一种  用继承的方式

///////////////////////////////////////////////

public class MyThread extends Thread {
    public void run() {
        //获取线程的名称getName()
        System.out.println("线程名称"+getName());
        for (int i = 0; i <20; i++) {
            System.out.println("MyThread--"+i);
        }
    }

//////////////////////////////////////////////////////////

public static void main(String[] args) {
        //返回当前代码正在执行的线程对象
        Thread th=Thread.currentThread();
        //获取该线程名称
        System.out.println(th.getName());
        //创建新线程
        MyThread thread=new MyThread();
        //开启线程  用start
        thread.start();
        for (int i = 0; i <20; i++) {
            System.out.println("main--"+i);
        }

****************************************************************************************************************************************************************************

第二种用实现接口的方式

//////////////////////////////////////////////

public class MyRunnable implements Runnable{
    public void run() {
        for (int i = 0; i <20; i++) {
            System.out.println("thread-0:"+i);
        }
    }

///////////////////////////////////////////////////////////////////////////

    public static void main(String[] args) {
        //创建线程任务对象
        MyRunnable mr=new MyRunnable();
        //创建thread类对象
        Thread th=new Thread(mr);
        //开启线程
        th.start();
        for (int i = 0; i < 20; i++) {
            System.out.println("main"+i);
        }
    }

posted on 2019-06-21 13:32  默示う梦璃  阅读(104)  评论(0)    收藏  举报