传统线程技术

创建并启动一个线程

方法一

1
2
3
4
5
6
7
8
9
10
public static void main(String[] args) {
Thread thd01 = new Thread("thd01") {
@Override
public void run() {
System.out.println("the Thread " + Thread.currentThread().getName() + " is executing.");
}
};
thd01.start();
System.out.println("the Thread " + Thread.currentThread().getName() + " is executing.");
}

方法二

1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) {
Thread thd02 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("the Thread " + Thread.currentThread().getName() + " is executing.");
}
});
thd02.setName("thd02");
thd02.start();
System.out.println("the Thread " + Thread.currentThread().getName() + " is executing.");
}

判断输出结果

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
System.out.println("the Thread01 " + Thread.currentThread().getName() + " is executing.");
}
}) {
/** 覆盖了Runnable中定义的方run() */
@Override
public void run() {
System.out.println("the Thread02 " + Thread.currentThread().getName() + " is executing.");
}
}.start();
}