マルチスレッドデータ同期のsynchronized同期方法-マルチスレッドアクセス臨界リソース
1495 ワード
package com.tools;
/**
*
* @author Administrator
*
*/
class TicketSouce implements Runnable
{
//
private int ticket=99;
public void run()
{
for(int i=1;i<200;i++)//
{
try {
// 1 , ,
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.sale();
}
}
public synchronized void sale()
{
if(ticket>0)
{
System.out.println(Thread.currentThread().getName()+" "+this.ticket--+" ");
}
}
}
public class Test {
public static void main(String args[])
{
TicketSouce mt=new TicketSouce();
// 10
new Thread(mt,"a").start();
new Thread(mt,"b").start();
new Thread(mt,"c").start();
new Thread(mt,"d").start();
new Thread(mt,"e").start();
new Thread(mt,"f").start();
new Thread(mt,"g").start();
new Thread(mt,"h").start();
new Thread(mt,"i").start();
new Thread(mt,"j").start();
}
}