------------------------------------------------------Android培训 Java培训 期待与您交流-----------------------------------------------------------
public class ThreadEstablish {
/**
* 线程创建的种形式
*/
public static void main(String[] args) {
/*
* 第一种:实现Thread的子类
*
*/
Thread thread1 = new Thread(){
//重写了Thread类的run();
@Override
public void run() {
System.out.println("thread1 is running :" + Thread.currentThread().getName());
}
};
thread1.start();
/*
*第二种:
*/
Thread thread2 = new Thread(new Runnable(){
@Override
public void run() {
System.out.println("thread2 is running :" + Thread.currentThread().getName());
}
});
thread2.start();
//以上看不出线程的效果,可以加以修改
//不写Thread.sleep(500);也行,写了更容易观察效果
/*
* 第一种:实现Thread的子类
*/
Thread thread3 = new Thread(){
//重写了Thread类的run();
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread3 is running :" + Thread.currentThread().getName());
}
}
};
thread3.start();
/*
*第二种:
*/
Thread thread4 = new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread4 is running :" + Thread.currentThread().getName());
}
}
});
thread4.start();
/*
* 第二种方式更能体现面向对象的思想
* 一个是线程对象thread,线程对象要运行代码runnable,
*/
/*
* 第三种也是第四种(这是一个组合,便于比较)
* 思考下面的那个线程会跑起来
*/
new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("runnable is running :" + Thread.currentThread().getName());
}
}
}){
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread is running :" + Thread.currentThread().getName());
}
}
}.start();
/*
* 我们知道实现Thread的子类重写了run方法,那么父类的run就失效了,而runnable调用的就是父类的run
* 如果不重写就找runnable,重写了就按重写的跑
* 具体请查看jdk
* 因此这里就只跑了thread is running
*/
}
}
------------------------------------------------------Android培训 Java培训 期待与您交流-----------------------------------------------------------