初稿:2017-11-19 22:43:30
创建线程的2种方法
2种方法的比较:能使用方法1就不使用方法2.
1 public class ThreadDemo {
2 public static void main(String[] args) {
3 /*启动新进程*/
4 Runner r = new Runner();
5 Thread t = new Thread(r);
6 t.start();
7
8 for(int i = 0;i <= 100; ++i) {
9 System.out.println("main : " + i);
10 }
11 }
12 }
13 /*定义一个新线程*/
14 class Runner implements Runnable {
15 public void run() {
16 for(int i = 0;i <= 100;++i) {
17 System.out.println("Runner : " + i);
18 }
19 }
20 }
main线程运行到插入进程的点,产生一个进程分支,main下面的代码和插入进程轮流执行,向前推进。
public class ThreadDemo {
public static void main(String[] args) {
/*启动新进程*/
Runner r = new Runner();
r.start();
for(int i = 0;i <= 100; ++i) {
System.out.println("main : " + i);
}
}
}
/*定义一个新线程*/
class Runner extends Thread {
public void run() {
for(int i = 0;i <= 100;++i) {
System.out.println("Runner : " + i);
}
}
}