Runable接口共享資源的代碼
public class TicketThreadR implements Runnable{
?? ?
??? private int num = 5;??????????? //總共票數(shù)設(shè)定為5張
?? ?
??? @Override
??? public void run() {
??????? for(int i=0; i<10; i++){
??????????? if(this.num>0){??????????? //打印買票信息
??????????????? System.out.println(Thread.currentThread().getName() + "買票: " + this.num--);
??????????? }
??????? }
??? }
??? public static void main(String[] args) {
??????? TicketThreadR ticketThread = new TicketThreadR();
?????? ?
??????? Thread th1 = new Thread(ticketThread);??? //線程一
??????? th1.setName("售票口一");
??????? Thread th2 = new Thread(ticketThread);??? //線程二
??????? th2.setName("售票口二");
??????? Thread th3 = new Thread(ticketThread);??? //線程三
??????? th3.setName("售票口三");
?????? ?
??????? th1.start();
??????? th2.start();
??????? th3.start();
??? }
}
標(biāo)簽: