- 直接继承Thread
- new Thread(new Runnable(){})
package Test;
/*
* start代表启动一个线程,不然run方法只是属于main线程的一部分
* new Thread(new Runnable(){public void run(){}}){public void run(){}}.start();
* 上面这个不会调用runnable的run方法,因为被覆盖了
* */
public class TheadUsage {
public static void main(String[] args){
//Run(); // 结果可能是0110,0先睡不代表0能先抢到cpu
useThread();
}
public static void Run(){
new Thread(new Runnable(){
public void run() {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}).start();
new Thread(new Runnable(){
public void run(){
System.out.println(Thread.currentThread().getName());
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}).start();
}
/*
* start还是会调用run方法的,如果run方法覆盖了,就调用覆盖的。不然源代码如下
* public void run() {
if (target != null) {
target.run();
}
}
*
* */
public static void useThread(){
ThreadUsage t1 = new ThreadUsage();
ThreadUsage t2 = new ThreadUsage();
t1.start(); // 结果都是不定的
t2.start();
}
}
class ThreadUsage extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}