62,614
社区成员
发帖
与我相关
我的任务
分享
class ti{//票
static int t=1;
static synchronized int getT(){
return t>10?-1:t++;
}
}
class mt extends Thread {//窗口
String name;
mt(String n){
name = n;
}
@Override
public void run() {
int i;
while((i=ti.getT())!=-1){
System.out.println(name+"卖出票:"+i);
System.out.flush();
try {
Thread.sleep(0);
} catch (InterruptedException ex) {
}
}
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new mt("1号窗口");
Thread t2 = new mt("2号窗口");
Thread t3 = new mt("3号窗口");
t1.start();
t2.start();
t3.start();
}
}
class mt extends Thread {
private static int count;
@Override
public void run() {
for (int i = 0; i < 100;) {
System.out.println(getName() + ":" + (++i));
if (i % 10 == 0) {
synchronized (this) {
count++;
}
while (i / 10 > count / 3) {//在这里等待其它线程
try {
Thread.sleep(0);
} catch (InterruptedException ex) {
}
}
}
}
try {
Thread.sleep(1);//为了让多线程明显 1ms
} catch (InterruptedException ex) {
}
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new mt();
Thread t2 = new mt();
Thread t3 = new mt();
t1.start();
t2.start();
t3.start();
}
}