本文以一个带有音乐播放的五子棋游戏为例记录自己在编写过程中遇到的有关java线程问题
编写环境:
- IDE:eclipse
- JDK:1.8
- 添加包:jlayer.jar
package gobang;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;//添加的jlayer.jar包
//背景音乐为.map3格式文件,以数字命名
//功能有开始播放,停止播放,下一首,上一首
public class musicPlayer implements Runnable {
// 不可以extends Thread。再重复使用thread。start会报java.lang.illegalthreadstateexception错误
private static int num = 1;
private final String firstMusic = "music/1.mp3";
static musicPlayer mp3;
private static String filename;//开始播放音乐文件的名字
private static Player player;
private static Thread thread;
private static volatile boolean flag = false;//用volatile修饰的变量,线程在每次使用变量的时候,都会读取变量修改后的最的值。volatile很容易被误用,用来进行原子性操作。使用的时候请注意。
public musicPlayer() {// 初始化创建播放音乐线程
filename = firstMusic;
thread = new Thread(this);
mp3 = this;
}
public static void play() {// 加载音乐文件
try {
// thread.sleep(100);
BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(filename));//文件输入流读取预定的第一首音乐文件
player = new Player(buffer);//设置对象Player
player.play();开始播放
} catch (Exception e) {
System.out.println(e);
}
}
public void run() {//重写thread的run方法,可以多次调用该方法,播放音乐文件
while (!flag) {//这里使用的判断是flag标志决定是否运行播放功能,在后面只要改变flag即可
play();
}
}
public static void startMusic() {
flag = false;
thread.start();//开始线程,自动加载自己的run方法,thread的start()和run()功能不一样,一个是启动线程,但可以什么都不做,一个在线程中运行东西
}
public static void stopMusic() {//停止播放音乐
player.close();
flag = true;
thread.run();
System.out.println(thread.isInterrupted());//可去掉,测试的时候用的
}
public static void loop() {//此功能没有用到,请省略掉。
if (player.isComplete()) {
next();
}
}
public static void next() {//下一首音乐
stopMusic();//停止当前音乐
num = num + 1;
String str = "music/" + num + ".mp3";
filename = str;
// player.close();
// mp3=new musicPlayer();
startMusic();
// thread=null;
}
public static void last() {
if (num == 1) {//判断当前的音乐是哪一首,1是第一首,6是最后一首,文件夹music中就有6首
return;
}
if (num == 6) {
num = 1;
}
if (num > 1 && num < 6) {
stopMusic();
num = num - 1;
String str = "music/" + num + ".mp3";
filename = str;
// player.close();编写的时候写的,可省略所有注释掉的代码
// thread=null;
// flag = false;
startMusic();
}
}
}
整个项目的代码:https://github.com/zhanbei1/MyOwnProject.git
第一次写,有什么问题望多多指教!!!