演练代码:卖票程序class Ticket implements Runnable
{
//定义票的张数
private int tick = 100;
//定义一个对象,用于synchronized()
Object obj = new Object();
//复写接口的run()方法
public void run()
{
while(true)
{
synchronized(obj)
{
if(tick>0)
{
//打印结果
System.out.println(Thread.currentThread().getName()+"....sale : "+ tick--);
}
}
}
}
}
class Test7
{
public static void main(String[] args)
{
//定义Ticket 的对象
Ticket t = new Ticket();
//定义四个线程
Thread t1 = new Thread(t,"线程一");
Thread t2 = new Thread(t,"线程二");
Thread t3 = new Thread(t,"线程三");
Thread t4 = new Thread(t,"线程四");
//开启四个线程
t1.start();
t2.start();
t3.start();
t4.start();
}
}
此代码中使用同步代码块解决了多线程的安全问题。但是多个线程需要判断锁,较为消耗资源
|
|