java中同步代码块和同步方法的使用
最近在学习多线程时发现了多线程存在隐患,这个隐患可以通过同步代码块或者同步方法来解决,凭借同步代码块和同步方法的使用,也能理解为什么同步方法执行起来比较慢,因为同步代码块和同步方法为了解决隐患而牺牲了执行效率。
例:
当前有一个购票方法,一共有100张票,需要通过开启三个线程来实现这个购票方法。
1.使用同步代码块实现购票:
class mythread implements Runnable{
private int tickets =100;
@Override
public void run() {
while (true){
synchronized (this) {
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "正在出售第张" + tickets-- + "票");
}
}
}
}
}
public class Test1 {
public static void main(String[] args) {
mythread t = new mythread();
Thread t0 = new Thread(t);
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t0.start();t1.start();t2.start();
}
}
2.使用同步方法实现购票方法
class mythread1 implements Runnable {
private int tickets = 100;
public synchronized void pay() {
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "正在出售第张" + tickets-- + "票");
}
}
@Override
public void run() {
while (true) {
pay();
}
}
}
public class Test2 {
public static void main(String[] args) {
mythread1 t = new mythread1();
Thread t0 = new Thread(t);
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t0.start();
t1.start();
t2.start();
}
}
总结:
要实现同步代码块或者是同步方法 需要添加关键字 synchronized来实现同步。
同步代码块需要将 synchronized关键字 括在要处理的共享数据的外面。
同步方法只需要在定义方法的时候添加synchronized关键字 然后再run方法里面调用就可以。
通过比较同步代码块和同步方法的使用,个人还是比较喜欢用同步方法来实现的。