Java多线程之中断机制(如何处理中断
1个回答
展开全部
boolean变量不适合你的需要。
你应把加载音乐的责任交给AudioClip来完成,其实就是它自己去加载音乐,这样方便管理。
public class AudioClip {
private Thread thread = null;
public synchronized void load(String url) {
if (thread != null) {
throw new IllegalStateException();
}
thread = new AudioClipLoader(url);
thread.start();
}
public void shutdown() {
Thread snapshot;
synchronized (this) {
snapshot = thread;
thread = null;
this.notifyAll();
}
if (snapshot != null) {
snapshot.interrupt();
}
}
private class AudioClipLoader extends Thread {
private String url;
public AudioClipLoader(String url) {
this.url = url;
}
@Override
public void run() {
while (true) {
Thread me = Thread.currentThread();
if (me != thread) {
break;
}
System.out.println("正在加载" + url + " ...");
try {
Thread.sleep(90 * 1000 * 60);
} catch (Exception ex) {
synchronized (AudioClip.this) {
me = Thread.currentThread();
if (me != thread) {// close by AudioClip
System.out.println("Shutdown by AudioClip!");
break;
}
// network connection exception
throw new RuntimeException(ex);
}
}
}
}
}
public static void main(String[] args) throws Exception {
AudioClip audioClip = new AudioClip();
audioClip.load("http://java.sun.com/");
Thread.sleep(5000);
audioClip.shutdown();
}
}
你应把加载音乐的责任交给AudioClip来完成,其实就是它自己去加载音乐,这样方便管理。
public class AudioClip {
private Thread thread = null;
public synchronized void load(String url) {
if (thread != null) {
throw new IllegalStateException();
}
thread = new AudioClipLoader(url);
thread.start();
}
public void shutdown() {
Thread snapshot;
synchronized (this) {
snapshot = thread;
thread = null;
this.notifyAll();
}
if (snapshot != null) {
snapshot.interrupt();
}
}
private class AudioClipLoader extends Thread {
private String url;
public AudioClipLoader(String url) {
this.url = url;
}
@Override
public void run() {
while (true) {
Thread me = Thread.currentThread();
if (me != thread) {
break;
}
System.out.println("正在加载" + url + " ...");
try {
Thread.sleep(90 * 1000 * 60);
} catch (Exception ex) {
synchronized (AudioClip.this) {
me = Thread.currentThread();
if (me != thread) {// close by AudioClip
System.out.println("Shutdown by AudioClip!");
break;
}
// network connection exception
throw new RuntimeException(ex);
}
}
}
}
}
public static void main(String[] args) throws Exception {
AudioClip audioClip = new AudioClip();
audioClip.load("http://java.sun.com/");
Thread.sleep(5000);
audioClip.shutdown();
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询