同步块和同步方法:(采用加锁机制)
public class Ticket {
public static void main(String [] atgs)
{
TicketSell t=new TicketSell();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
class TicketSell implements Runnable{
int index=100;
Object o=new Object();
public void run()
{
/*synchronized(o)
{
while(index>0)
{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("There are only "+index+" tickets");
index--;
}
}*/ //注视起来的这一段代码为同步块;
lock();
}
public synchronized void lock()
{
while(index>0)
{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("There are only "+index+" tickets");
index--;
}
}
}