• java多线程中run和start区别


    run只是Thread里面的一个普通方法,start是启动线程的方法。
    start()方法让一个线程进入就绪队列等待分配 cpu, 分到 cpu 后才调用实现的run()方法。
    start()方法不能重复调用, 如果重复调用会抛出异常。
    而 run 方法是业务逻辑实现的地方, 本质上和任意一个类的任意一个成员方
    法并没有任何区别, 可以重复执行, 也可以被单独调用。

    1.start()方法来启动线程,无需等待run方法体代码执行完毕,可以直接继续执行下面的代码;
    jvm通过调用Thread类的start()方法来启动一个线程, 这时此线程是处于就绪状态, 并没有运行。
    然后通过此Thread类调用方法run()来完成其运行操作的, 这里方法run()称为线程体,它包含了要执行的这个线程的内容, run方法运行结束, 此线程终止。
    然后其他线程再抢cpu的控制权接着执行,这是真正实现了多线程。

    2.run()方法当作普通方法的方式调用。程序还是要顺序执行,要等待run方法体执行完毕后,才可继续执行下面的代码; 程序中只有主线程——这一个线程,其程序执行路径还是只有一条。这并非多线程,还只是单线程。

    public class MyThread1 extends Thread {
        @Override
        public void run() {
            try {
                System.out.println("run threadName="+ this.currentThread().getName()+"begin");
                Thread.sleep(2000);
                System.out.println("run threadName="+this.currentThread().getName()+"end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public class Run1 {
        public static void main(String[] args) {
            final MyThread1 myThread1 = new MyThread1();
            System.out.println("begin="+System.currentTimeMillis());
            myThread1.run();
            System.out.println("end="+System.currentTimeMillis());
        }
    }

    public class Run2 {
        public static void main(String[] args) {
            final MyThread1 myThread2 = new MyThread1();
            System.out.println("begin="+System.currentTimeMillis());
            myThread2.start();
            System.out.println("end="+System.currentTimeMillis());
        }
    }

  • 相关阅读:
    smarty
    js进阶
    JS 基础
    php之面向对象(2)
    php之面向对象(1)
    PHP之图形处理
    PHP代码分离
    PHP文件上传与安全
    PHP substr截取中文字符出现乱码的问题解疑
    关于学习方法
  • 原文地址:https://www.cnblogs.com/weigy/p/12409575.html
Copyright © 2020-2023  润新知