线程:代码一条条的执行,分出另外一条线执行线路,多条线路同时并行执行。
创建线程的两种常见方法:
1、new Thread子类
2、new Runnable dui
public static void main(String[] args) {
Thread thread = new Thread(){ //创建线程的方式1.new Thread 子类
@Override
public void run() {
while(true){ //线程不停的运行
try {
Thread.sleep(1000); //使当前线程休眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1:" + Thread.currentThread().getName());
System.out.println("1.1:" + this.getName());
}
}
};
thread.start();
//创建线程的方法2 new Runnable对象
Thread thread2 = new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2:" + Thread.currentThread().getName());
}
}
});
thread2.start();
运行结果:
注意:线程启动之后,会先去找自己的run()方法,当找不到自己的run()方法才去找其父类的run()方法
例子:
/*该方法会执行Thread子类的run方法, 原因:执行start之后会先去找自己的run方法即Thread自己的run方法(即1),如果没有则会去找父类的run方法(即2)*/
new Thread(
new Runnable(){
public void run() {//1
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("runnable :" + Thread.currentThread().getName());
}
}
}
){
public void run() {//2
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread :" + Thread.currentThread().getName());
}
}
}.start();
}
执行结果: