java多线程如何让一个线程只执行一次?我目前只能是检测到getname()然后用wait()方法。想知道还有没其他方法?
public class TicketSale {
public static void main(String[] args) {
Runnable r1=new Ticket();
Thread t1=new Thread(r1);
Thread t2=new Thread(r1);
Thread t3=new Thread(r1);
t1.setName("黄牛党");
t2.setName("桃跑跑");
t3.setName("张票票");
t1.start();
t2.start();
t3.start();
}
}
class Ticket implements Runnable{
private int ticket=10;
private int num=1;
public synchronized void sale(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(ticket>0){
System.out.println(Thread.currentThread().getName()+"抢到第"+(num++)+
"张票。剩余"+((ticket--)-1)+"张票。");
}
if(ticket==0){
notify();
System.out.println("票已全部售完");
}
if("黄牛党".equals(Thread.currentThread().getName())){
Thread.currentThread().interrupted();
}
}
@Override
public void run() {
while(num<10){
sale();
}
}
}