线程的三种创建方式
/*使用extends Thread方式*/
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"--"+i);
}
}
}
MyThread thread = new MyThread();
thread.start()
/*使用Runnable方式创建线程*/
class MyThread2 implements Runnable{
@Override
public void run() {
for (int i = 0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"--"+i);
}
}
}
Thread thread = new Thread(new MyThread2());
thread.start();
//使用callable方式创建线程
class MyThread3 implements Callable<String>{
@Override
public String call() throws Exception {
String result = "我叫"+Thread.currentThread().getName();
return result;
}
}
MyThread3 thread3 = new MyThread3();
FutureTask<String> task = new FutureTask<String>(thread3);
new Thread(task).start();
String result = task.get();
System.out.println(result);
线程的终止方式
- 使用退出标志退出线程
最常使用的方式其实现方式是:定义一个boolean型的标志位,在线程run()方法中根据这个标志位是true还是false来判断是否推出,这种情况一般是将任务放在run()方法中的一个while循环中执行。
- Interrupt 方法结束线程
1.线程处于阻塞状态。如使用了sleep,同步锁的wait,socket中的receiver,accept等方法时,会使线程处于阻塞状态。
TIP:使用interrupt方法结束线程的时候,一定要先捕获InterruptedException异常之后通过break来跳出循环,才能正常结束run方法。
2.线程未处于阻塞状态。使用isInterrupter()判断线程的中断标志来退出循环。当使用interrupt()方法时,中断标志就会置true,和自定义的标志来控制循环是一样的道理。
- stop 方法终止线程
使用stop方法可以强行终止正在运行或挂起的线程。我们可以使用如下的代码来终止线程:
thread.stop();
采用stop是不安全的,主要影响点如下:
(1)thread.stop()调用之后,创建子线程的线程就会抛出ThreadDeatherror的错误;
(2)调用stop会释放子线程所持有的所有锁。导致该线程所持有的所有锁突然释放(不可控制),那么被保护数据就有可能呈现不一致性。
总结
- 线程创建:推荐使用Runnable或则Callable方式创建线程,相比集成,接口实现可以更加灵活,不会受限于Java的单继承机制。
- 线程终止:线程终止推荐使用标志位或Interrupt方式终止,stop方式对线程不安全,易导致数据不一致。