public class ThreadTestDemo {
private int threadNum;//当前线程
private int num;//输出的数字
public ThreadTestDemo(int threadNum, int num) {
super();
this.threadNum = threadNum;
this.num = num;
}
//内部线程类
static class PrintThread extends Thread{
private int mThreadNum;//线程数
private ThreadTestDemo demo;//当前所在的类
public PrintThread(int threadNum,ThreadTestDemo demo) {
this.mThreadNum = threadNum;
this.demo = demo;
}
@Override
public void run() {
System.out.println("当前线程是:"+ mThreadNum);
//为demo上锁,每次只能有一个线程执行,这是关键
synchronized (demo) {
for(int i = 1;i<= 3;i++){
while(true){
System.out.println("Thread"+mThreadNum+"*****");
//如果当前线程是demo中将要运行的线程,则跳出循环,否则说明其他线程正在运行,资源被占用,demo等待
if(mThreadNum == demo.threadNum){
System.out.println("Thread "+mThreadNum+" is running");
break;
}else{
try {
demo.wait();
System.out.println("demo-thread "+demo.threadNum+" is waiting");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//当前线程抢到资源后,执行循环操作
for(int j= 1;j<=5;j++){
System.out.println("Thread"+mThreadNum+":"+(++demo.num));
}
//赋予demo即将要执行的thread,并通知demo
demo.threadNum = demo.threadNum%3+1;
demo.notifyAll();
}
}
}
}