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();
}
}
在播放声音的外层套一个
private flag=true;
while(flag==true){}
想停止的话
flag===false;
public class TestThread2
{
public static void main(String []args)
{
Test r=new Test();
Thread t=new Thread(r);
for(int i=0;i<100;i++){
t.start();
}
r.shutdown();
}
}
class Test implements Runnable
{
private boolean flag=true;
public void run(){
while(flag==true){
System.out.println("Test Running ");
}
}
public void shutdown()
{
flag=false;
}
}