格式:在方法声明上加上 synchronized
_public synchronized void method() {
可能会产生线程安全问题的代码
}_
注:同步方法中的锁对象是 this
再对售票的案例进行改进:
public class Ticket implements Runnable{
int T = 10;
//定义锁对象
Object lock = new Object();
@Override
public void run() {
while (true)
{
//同步方法
method();
}
}
private synchronized void method()
{
if(T > 0)
{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + T–);
}
}
}
同步方法也能解决线程安全问题
(2) 静态同步方法
格式:在方法声明上加上 static synchronized
_public static synchron