两种常见的实现java多线程的方式

package nxr.cn;
/**
 * 第一种方法:创建线程
 * 1.继承Thread+重写run
 * 2.启动 start
 * @author 26651
 *
 */
public class StartThread extends Thread{
    /**
     * 线程入口点
     */
    @Override
    public void run() {
        for(int i=0;i<20;i++) {
            System.out.println("听歌");
        }
    }
    public static void main(String[] args) {
        //创建子类对象
        StartThread st = new StartThread();
        //启动线程
        st.start();   //把线程交给 cpu 调度
        //st.run();     //普通方法的调用
        
        for(int i=0;i<20;i++) {
            System.out.println("打游戏");
        }
    }
}

 

package nxr.cn;
/**
 * 创建线程第二种方式
 * 1.实现Runable+重写run
 * 2.启动:创建(实现类对象  + Thread代理对象) + start
 * @author 26651
 *
 */
public class StartThread2 implements Runnable{
    /**
     * 线程入口点(线程体)
     */
    @Override
    public void run() {
        for(int i=0;i<20;i++) {
            System.out.println("一边听歌");
        }
    }
    public static void main(String[] args) {
//        //创建实现类对象
//        StartThread2 st = new StartThread2();
//        //创建代理类对象
//        Thread tr = new Thread(st);
//        //启动线程
//        tr.start();   //把线程交给 cpu 调度
//        //st.run();     //普通方法的调用
        new Thread(new StartThread2()).start();  //对象只使用一次,使用匿名对象
        for(int i=0;i<20;i++) {
            System.out.println("一边写代码");
        }
    }
}

 

posted @ 2019-05-28 16:48  飞蝎儿  阅读(155)  评论(0编辑  收藏  举报