一. 直接调用run()方法
public class Two_Thread implements Runnable {
public static void main(String[] args) {
// TODO Auto-generated method stub
Two_Thread R = new Two_Thread();
R.run(); // 直接调用run()方法, 而不是start()方法启动线程
System.out.println(Thread.currentThread().getName()+" back to main");
}
@Override
public void run() {
// TODO Auto-generated method stub
increate();
}
private void increate() {
// TODO Auto-generated method stub
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+" i = "+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
无论什么时候,打印的log都是以下不变:
main i = 0
main i = 1
main i = 2
main i = 3
main i = 4
main back to main
由log可以看出,run()方法是通过main线程启动的,并且它不不具有任何内在的线程能力(即总是执行完run方法,才打印main back to main)。如果要实现线程行为,必须采用start()方法。
二.添加一个线程t1. 并且去掉线程休眠 Thread.sleep(1000);
public class Two_Thread implements Runnable {
public static void main(String[] args) {
// TODO Auto-generated method stub
Two_Thread R = new Two_Thread();
Thread t1 = new Thread(R,"1"); //用Runnable对象1初始化
t1.start(); //通过start()方法启动线程
R.run();//调用Runable对象中的run()方法
System.out.println(Thread.currentThread().getName()+" back to main");
}
@Override
public void run() {
// TODO Auto-generated method stub
increate();
}
private void increate() {
// TODO Auto-generated method stub
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+" i = "+i);
}
}
}
此时打印的log是随机的:但是无论什么时候,这句“main back to main”log,一定是在执行完main i = 4之后才会执行。因为在主线程中,这俩句是顺序执行的。
情况1:
main i = 0
1 i = 0
main i = 1
1 i = 1
main i = 2
1 i = 2
main i = 3
1 i = 3
main i = 4
1 i = 4
main back to main
情况2:
1 i = 0
main i = 0
1 i = 1
main i = 1
1 i = 2
main i = 2
1 i = 3
main i = 3
main i = 4
main back to main
1 i = 4