1、什么是线程
什么是线程?
百度的说法:线程,有时被称为轻量级进程,是程序执行流的最小单元。
其实线程就是进程中的一个执行单元,在一个进程中如果有多个线程在执行,那就被称为多线程。
操作系统中进程和线程的概念也对我们理解线程与进程的关系有帮助:
http://m.blog.youkuaiyun.com/blog/dwyers/38367427
2、线程的“同时执行”是如何实现的?
这里涉及到并发和并行的概念
有些时候线程的“同时执行”并不是真正的同时执行,这是由操作系统的时间片轮巡方式形成的。对于单CPU的操作系统,一个时间只能让一个线程启动,但是不断的切换执行不同的线程,造成了我们看到的“同时执行”,这样的方式就叫做并发。
对于多CPU系统,才可以真正实现不同线程同时运行,这样称之为并行。
3、Java中线程的实现方式有哪些?
Java线程的主要实现方式是继承Thread类和实现Runnable接口,Runnable接口一般在线程对象已经继承了一个类之后(无法再继承Thread了)时使用,具体怎么做就不赘述了。要注意的是创建一个线程对象之后要开启才能执行这个线程的run方法。
4、线程对象有哪些常用的方法?
这篇博文详细介绍了interrupt的用法
http://www.360doc.com/content/11/0413/14/4154133_109311159.shtml
这篇博文详细介绍了interrupt、isInterrupt、interrupted的用法
http://blog.youkuaiyun.com/gtuu0123/article/details/6040105
线程中的方法有很多,我们就中断线程的方法说一些内容:
中断一个线程有哪些方式呢?
(1)Thread.stop()、Thread.suspend()、 Thread.resume() 和Runtime.runFinalizersOnExit() 这些终止线程运行的方法 。这些方法已经被废弃,使用它们是极端不安全的,既然不安全就不多说了。
(2)Thread.interrupt() 方法是很好的选择。但是使用的时候我们必须好好理解一下它的用处。
我们可以在程序中尝试使用,本以为它可以产生类似于stop()的效果,然而并不是,它没有使线程中断。
看下面一段代码:
class ThreadDemo implements Runnable{
public void run(){
while(true){
System.out.println( "Thread is running..." );
long time = System.currentTimeMillis();//去系统时间的毫秒数
while((System.currentTimeMillis()-time < 1000)) {}
}
}
}
public class testRunnable{
public static void main(String args[]){
ThreadDemo td = new ThreadDemo();
Thread t = new Thread(td);
t.start();
t.interrupt();
}
}
即使在使用了interrupt之后,线程仍然完全没有中断的意思。
那么interrupt的正确使用方式是怎样的呢?
//interrupted的经典使用代码
public void run(){
try{
....
while(!Thread.currentThread().isInterrupted()&& more work to do){
// do more work;
}
}catch(InterruptedException e){
// thread was interrupted during sleep or wait
}
finally{
// cleanup, if required
}
}
这样才是正确的,在我们调用interrupt之后,线程的中断状态被设置了,所以我们执行isInterrupted()后得到的是true,线程中的循环将不再执行,这个线程也就被中断了。