方法1:
在唯一的对象中 声明一个属性 一定不能是基本数据类型 一般是Object类型
使用synchronized代码块 括号中必须放这个锁 然后将代码放到synchronized代码块中
代码就变成 线程安全的代码 整个代码资源就会同步
package ls190521;
public class SellTicket implements Runnable
{
private int ticket=100;
private Object lock=new Object();
public void run()
{
synchronized (lock)
{
for(int i=1;i<=30&&ticket>0;i++)
{
System.out.println(Thread.currentThread().getName()+"当前还剩"+ticket+"张票");
ticket--;
}
}
}
public static void main(String[] args)
{
SellTicket sellticket=new SellTicket();
Thread thread1=new Thread(sellticket);
Thread thread2=new Thread(sellticket);
Thread thread3=new Thread(sellticket);
Thread thread4=new Thread(sellticket);
Thread thread5=new Thread(sellticket);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
或者把run方法改成:
public void run()
{
while(true)
{
synchronized (lock)
{
if(ticket<=0)
{
break;
}
System.out.println(Thread.currentThread().getName()+"当前还剩"+ticket+"张票");
ticket--;
}
}
}
运行结果:
方法2:
如果在run方法中调用其它的方法 其他类的方法要加锁 synchronized
package ls190521;
public class SellTicket implements Runnable
{
private int ticket=100;
private Object lock=new Object();
public void run()
{
dosomthing();
}
public void dosomthing()
{
synchronized (lock)
{
for(int i=1;i<=30&&ticket>0;i++)
{
System.out.println(Thread.currentThread().getName()+"当前还剩"+ticket+"张票");
ticket--;
}
}
}
public static void main(String[] args)
{
SellTicket sellticket=new SellTicket();
Thread thread1=new Thread(sellticket);
Thread thread2=new Thread(sellticket);
Thread thread3=new Thread(sellticket);
Thread thread4=new Thread(sellticket);
Thread thread5=new Thread(sellticket);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
可以达到同样的效果
方法3:
如果当前使用的runabled接口 可以直接将自己作为锁 因为runabled接口的实现有且只有一个
package ls190521;
public class SellTicket implements Runnable
{
private int ticket=100;
public void run()
{
synchronized (this)
{
for(int i=1;i<=30&&ticket>0;i++)
{
System.out.println(Thread.currentThread().getName()+"当前还剩"+ticket+"张票");
ticket--;
}
}
}
public static void main(String[] args)
{
SellTicket sellticket=new SellTicket();
Thread thread1=new Thread(sellticket);
Thread thread2=new Thread(sellticket);
Thread thread3=new Thread(sellticket);
Thread thread4=new Thread(sellticket);
Thread thread5=new Thread(sellticket);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}