1、run()/start()的区别
run()方法只是thread的一个普通方法调用,还是在主线程里执行,所有的线程要顺序执行,一个线程执行完毕后才可以继续执行下面的线程,这样无法达到写线程的目的(A线程从3到1执行完毕后,B才开始执行从3到1,他们都在一个主线程里,顺序执行)
start()方法来启动线程,新线程会执行相应的run()方法,真正实现了多线程运行,这时无需等待run方法体代码执行完毕而可以直接继续执行下面的代码,调用start()后,线程会被放到等待队列,等待CPU调度,并不一定马上开始执行,只是将这个线程置于可动行状态,然后通过JVM,线程Thread会调用run()方法,执行本线程的线程体。先调用start后调用run(线程C和D是一起执行的,从3到1)
package Thread20170329;
class Thread20170329 extends Thread{
private String name;
public Thread20170329(String name) {
this.name = name;
}
public void run() {
int i = 3;
while(i > 0) {
System.out.println(this.name + ":" + (i--));
}
}
public static void main(String[] args) {
Thread20170329 test1 = new Thread20170329("A");
Thread20170329 test2 = new Thread20170329("B");
Thread20170329 test3 = new Thread20170329("C");
Thread20170329 test4 = new Thread20170329("D");
test1.run();
test2.run();
test3.start();
test4.start();
if(Thread.activeCount()>=1)
{
Thread.yield();
}
}
}
执行结果如下:
2、Thread类和Runable接口的区别
继承Thread类的线程,每个线程完成各自的任务(Thread-0和Thread-1分别从5执行到1),实现Runnable接口的几个线程,共同去完成同一个任务(线程A和B线一起执行从5到1)
package Runable20170329;
class MyThread implements Runnable{
int i = 5;
public void run() {
while(i > 0) {
System.out.println(Thread.currentThread().getName() + ":" + (i--));
}
}
}
class MyThread1 extends Thread{
int i = 5;
public void run() {
while(i > 0) {
System.out.println(Thread.currentThread().getName() + ":" + (i--));
}
}
}
public class ThreadRunable20170329 {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread r = new MyThread();
Thread t1 = new Thread(r,"A");
Thread t2 = new Thread(r,"B");
t1.start();
t2.start();
MyThread1 mt1 = new MyThread1();
MyThread1 mt2 = new MyThread1();
mt1.start();
mt2.start();
}
}
执行结果如下:
用图表示: