实现线程的三种方法
1.继承线程类Thread
2.实现接口Runnable
3.实现Callable类
继承Thread
public class A extends Thread{
public void run(){
for (int i = 0; i < 5; i++) {
System.out.println("A thread "+i+" 执行");
try{
Thread.sleep(7);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
通过接口Runnable
public class ThreadB implements Runnable{
public void run(){
for (int i = 0; i < 100000; i++) {
System.out.println("back Thread execute No.+"+i);
try{
Thread.sleep(7);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
通过Callable实现
public class C implements Callable<String>{
public String call() throws Exception{
try{
Thread.sleep(500);
}catch(InterruptedException e){
e.printStackTrace();
}
return "this is call ";
}
}
线程通过Thread.interruput()进行终端,
在线程中可以通过 Boolean isInterruputed()进行判断是否有中断请求
boolean interrupted()测试当前线程是否已经中断
线程的生命周期有一下几个阶段
new 创建
runnable 就绪状态
running 运行状态
blocked 堵塞状态
dead 死亡状态
什么是守护线程?
简单的溯就是后台线程,不需要手动去通知管理其状态,
在线程开始前通过setDeamon(boolean on)进行设置
A a = new A();
ThreadB threadB = new ThreadB();
Thread b = new Thread(threadB);
b.setDaemon(true);
a.start();
b.start();
A a = new A();
a.start();
ThreadB threadB = new ThreadB();
for (int i = 0; i < 5; i++) {
new Thread(threadB,"Thread B No. "+i).start();
}
Thread thread = Thread.currentThread();
System.out.println("this is main Thread "+thread.getName());
Thread thread = new Thread(new Main(),"main thread");
System.out.println("thread is start");
thread.start();
Thread.sleep(500);
System.out.println("interupt thread");
thread.interrupt();
System.out.println("thread is interupt: "+thread.isInterrupted());
System.out.println(thread.getState());
前台线程是保证执行完,而后台线程则不一定保证执行完
当非守护线程结束退出时,即使守护线程仍在进行,进程仍将结束。即有可能当进程结束时,守护线程仍在运行。