区别
run()
只是一个普通的方法调用,不会开启新的线程。
start()
会开启新的线程,分配新的资源。里面的变量互不影响。
实例
package multithreading;public class MyThread extends Thread {String flag;public MyThread(String flag) {this.flag = flag;}@Overridepublic void run() {String tname = Thread.currentThread().getName();System.out.println(tname + "线程的run方法被调用……");for (int i = 0; i < 5; i++) {try {Thread.sleep(200);System.out.println(tname + "...." + flag);} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) {MyThread t1 = new MyThread("a");MyThread t2 = new MyThread("b");MyThread t3 = new MyThread("c");t1.run();t2.run();t3.run();System.out.println("-------------分割线-----------");t1.start();t2.start();t3.start();}
}
运行结果
main线程的run方法被调用……
main....a
main....a
main....a
main....a
main....a
main线程的run方法被调用……
main....b
main....b
main....b
main....b
main....b
main线程的run方法被调用……
main....c
main....c
main....c
main....c
main....c
-------------分割线-----------
Thread-0线程的run方法被调用……
Thread-2线程的run方法被调用……
Thread-1线程的run方法被调用……
Thread-0....a
Thread-2....c
Thread-1....b
Thread-2....c
Thread-0....a
Thread-1....b
Thread-0....a
Thread-2....c
Thread-1....b
Thread-2....c
Thread-0....a
Thread-1....b
Thread-2....c
Thread-0....a
Thread-1....b