一,正确的中断线程的操作:有两种方法
- 1,interrupt()结合return操作
- 2,interrupt()结合抛异常操作
public class MyThread extends Thread {
@Override
public void run() {
super.run();
//1,interrupt()结合return操作
while (true) {
if (this.isInterrupted()) {
System.out.println("ֹ执行了ͣinterrupt冲断当前线程操作");
return;
}
System.out.println("当前时间=" + System.currentTimeMillis());
}
/*
//2,interrupt()结合抛异常操作
try {
while (true) {
if (this.isInterrupted()) {
System.out.println("ֹ执行了ͣinterrupt冲断当前线程操作");
throw new InterruptedException();
}
System.out.println("当前时间=" + System.currentTimeMillis());
}
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("捕获到了抛异常中断线程");
}*/
}
}
public static void main(String[] args) throws InterruptedException {
MyThread myThread=new MyThread();
myThread.start();
Thread.sleep(2000);
myThread.interrupt();
}
二,join的使用
public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread threadTest = new MyThread();
threadTest.start();
threadTest.join();//主线程需要等threadTest(子线程)执行完以后再执行下面操作
System.out.println("我想当threadTest对象执行完毕后我再执行");
}
static public class MyThread extends Thread {
@Override
public void run() {
System.out.println("我想先执行");
}
}
}
三,wait和notify结合使用
/**
* A线程等待B线程来唤醒
*/
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
ThreadA threadA = new ThreadA(lock);
threadA.start();
ThreadB threadB = new ThreadB(lock);
threadB.start();
}
public static class ThreadA extends Thread {
private Object lock;
public ThreadA(Object lock) {
this.lock = lock;
}
@Override
public void run() {
super.run();
synchronized (lock) {
System.out.println("A开始等待" + System.currentTimeMillis());
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("A等待结束" + System.currentTimeMillis());
}
}
}
public static class ThreadB extends Thread {
Object lock;
public ThreadB(Object lock) {
this.lock = lock;
}
@Override
public void run() {
super.run();
synchronized (lock) {
for (int i = 0; i < 10; i++) {
MyList.add(i);
if (MyList.size() == 5) {
lock.notify();
System.out.println("B发出唤醒");
}
}
}
}
}
}
网友评论