//创建线程的三种方式:1继承Thread类,覆盖run方法 2.实现Runnalbe接口
3.内部类(new一个线程 和新建一个接口。
package com.hawkol.thread1;
public class Test {
//1.启动一个线程要调用start(),使用run是单线程顺序执行
//2.停止一个线程通过设置一个flag标记,run方法返回循环正常结束
//3.interrupt 中断,会抛出异常
public static void main(String[] args) {
MyThread myThread=new MyThread();
myThread.setName("MyThread-myThread");
myThread.start();
Thread thread=new Thread(new MyThread2());
thread.setName("MyThread2-thread");
thread.start();
//4.类部类-传入接口
new Thread(new Runnable() {
@Override
public void run() {
for(int k=1;k<=100;k++){
System.out.println(Thread.currentThread().getName()+":"+k);
try {
thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
//3.内部类1
new Thread("内部类1"){
public void run() {
super.run();
for(int k=1;k<=100;k++){
System.out.println(Thread.currentThread().getName()+":"+k);
try {
thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
myThread.run();//使用run是单线程顺序执行
thread.run();
}
}
//实现Runnable接口比较好用,因为类可以实现多接口,但只能单继承
//2.实现Runnalbe接口
class MyThread2 implements Runnable{
@Override
public void run() {
for(int j=1;j<=100;j++){
System.out.println(Thread.currentThread().getName()+":"+j);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//1继承Thread类,覆盖run方法
class MyThread extends Thread{
@Override
public void run() {
super.run();
for(int i=1;i<=100;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
//if(i>=5)
MyThread.currentThread().interrupt();//线程中断会抛出异常
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}