Threadstart()和run()方法的区别 | 您所在的位置:网站首页 › thread和threadstart › Threadstart()和run()方法的区别 |
用Thread类的start()方法来启动一个线程,这时此线程处于就绪(可运行)状态,并没有运行,一旦得到cpu时间片,就开始执行run()方法,这里方法 run()称为线程体,它包含了要执行的这个线程的内容,Run方法运行结束,此线程随即终止。用start是多线程各自运行,线程之间不会共享数据 run()方法只是类的一个普通方法而已,如果直接调用Run方法,程序中依然只有主线程这一个线程,其程序执行路径还是只有一条,还是要顺序执行,还是要等待run方法体执行完毕后才可继续执行下面的代码,这样就没有达到写线程的目的。总结:调用start方法方可启动线程,而run方法只是thread的一个普通方法调用,还是在主线程里执行。这两个方法应该都比较熟悉,把需要并行处理的代码放在run()方法中,start()方法启动线程将自动调用 run()方法,这是由jvm的内存机制规定的。并且run()方法必须是public访问权限,返回值类型为void.。run()方法始终是当前线程,因而数据可以共享 //四个线程共卖100张票 public class RunnableTest { public static void main(String[] args) { Runnable runnable=new MyThread(); new Thread(runnable).start(); new Thread(runnable).start(); new Thread(runnable).start(); new Thread(runnable).start(); } public static class MyThread implements Runnable{ private int tickets=100; public void run() { while(tickets>0){ System.out.println(Thread.currentThread().getName()+"卖出第【"+tickets--+"】张火车票"); } } } } //使用Thread类模拟4个售票窗口共同卖100张火车票的程序,实际上是各卖100张 public class ThreadTest2 {
public static void main(String[] args){ new MyThread().start(); new MyThread().start(); new MyThread().start(); new MyThread().start(); } } class MyThread extends Thread{ private int tickets=100; public void run() { while(tickets>0){ System.out.println(this.getName()+"卖出第【"+tickets--+"】张火车票"); } } }
|
CopyRight 2018-2019 实验室设备网 版权所有 |