只要是new一个共享资源就行
runnable (new一个ticket,因为多个线程可以使用一个目标对象)
package ticketThread; class ticketP { int ticket=100; void sale() { this.ticket--; } } class ticket extends Thread { private ticketP tk; public ticket(ticketP tk) { this.tk=tk; } public void run() { synchronized(this.tk) { while(tk.ticket>0) { System.out.println("sale : " + Thread.currentThread().getName() + " " + tk.ticket); tk.sale(); } } } public static void main(String[] args) { ticketP tk1=new ticketP(); ticket t1=new ticket(tk1); ticket t2=new ticket(tk1); ticket t3=new ticket(tk1); ticket t4=new ticket(tk1); t1.start(); t2.start(); t3.start(); t4.start(); } }
synchronized (new一个ticketP,用synchronized对它互斥访问)
class ticket implements Runnable { } private int tk=100; public void run() { while(tk>0) { System.out.println("sale : " + Thread.currentThread().getName() + " " +tk--); } } public static void main(String[] args) { ticket tk1=new ticket(); Thread t1=new Thread(tk1); Thread t2=new Thread(tk1); Thread t3=new Thread(tk1); Thread t4=new Thread(tk1); t1.start(); t2.start(); t3.start(); t4.start(); } }