java 对线程的常用方法大概有以下几个
一、线程的启动与中止
java 启动线程的方式大概有以下几种
打开Thread上的注释:可以清楚看到设计者给我们提供的样例
启动:注callable 方式暂时不做演示
1、继承Thread 类
2、实现Runnable
/**
* 线程启动演示
*
* @author ckj
*
*/
public class MyThread {
private static class UserThread extends Thread {
@Override
public void run() {
super.run();
System.out.println("I am extends Thread");
}
}
private static class UserRunnable implements Runnable {
public void run() {
System.out.println("I am implements Runnable");
}
}
public static void main(String[] args) {
UserThread userThread = new UserThread();
userThread.start();
UserRunnable userRunnable = new UserRunnable();
new Thread(userRunnable).start();
}
}
Thread 和 Runnable 的区别:
可以看到Thread 是一个类而Runnable 是一个接口,Thread 可以接收任意一个Runnable的实例并执行。所以可以认为Runnable 只是对业务的抽象,而Thread 则是Java对线程的抽象。
中止:
1、线程自然运行中止
2、stop
stop() 停止当前线程,但是在Thread 类中打上了@Deprecated 注解,也就是设计者不建议我们使用,原因是stop 终结一个线程是不会保证线程的资源正常释放(比如锁),会导致程序可能工作在不确定的状态下,同理resume() 恢复、suspend() 暂停,这两个方法也有同样的不释放资源的问题。所以尽量不使用此类方法。
3、interrupt() 中断
由于stop() 的各种问题,设计者给我们提供安全的中止方法,通过调用线程的interrupt()对其进行中断操作
/**
* 线程中断演示
* @author ckj
*
*/
public class InterruptThread {
private static class UserThread extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
String threadName = this.currentThread().getName();
while (!isInterrupted()) { //判断标识位
System.out.println(threadName + "interrrupt flag=" + isInterrupted());
}
System.out.println(threadName+" interrrupt flag ="+isInterrupted());
}
}
public static void main(String[] args) throws InterruptedException {
Thread userThread = new UserThread();
userThread.start();
Thread.sleep(10);
userThread.interrupt();//中断线程,其实设置线程的标识位true
}
}
线程通过方法 isInterrupted()来进行判断是否被中断。
如果一个线程处于了阻塞状态(如线程调用了 thread.sleep、thread.join、 thread.wait 等),则在线程在检查中断标示时如果发现中断标示为 true,则会在 这些阻塞方法调用处抛出 InterruptedException 异常,并且在抛出异常后会立即 将线程的中断标示位清除,即重新设置为 false。
/**
* 线程中断异常演示
* @author ckj
*
*/
public class InterruptThreadEx {
private static class UserThread extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
String threadName = this.currentThread().getName();
while (!isInterrupted()) { //判断标识位
try {
Thread.sleep(100);
System.out.println(threadName + "interrrupt flag=" + isInterrupted());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
//
System.out.println(threadName + "interrrupt flag=" + isInterrupted());
//重复释放资源
interrupt();
e.printStackTrace();
}
}
System.out.println(threadName+" interrrupt flag ="+isInterrupted());
}
}
public static void main(String[] args) throws InterruptedException {
Thread userThread = new UserThread();
userThread.start();
userThread.sleep(500);
userThread.interrupt();//中断线程,其实设置线程的标识位true
}
}
注意:处于死锁状态的线程无法被中断