请解释 volatile 与 synchronized 的区别?
volatile主要在属性上使用,而synchronized是在代码块与方法上使用的
volatile无法描述同步的处理,它只是一种直接内存的处理,避免了副本的操作,而synchronized是实现同步的
案例:卖票
class MyThread4 implements Runnable{
private volatile int ticket = 5; // 直接内存操作
@Override
public void run() {
synchronized (this) {
while(this.ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "卖票处理,ticket = " + this.ticket --);
}
}
}
}
public class SynchronizedDemo {
public static void main(String[] args) {
MyThread4 mt = new MyThread4();
new Thread(mt, "票贩子A").start();
new Thread(mt, "票贩子B").start();
new Thread(mt, "票贩子C").start();
}
}
多线程案例分析
设计4个线程对象,两个线程加两个线程减,共用一个资源
public class ThreadCalculateDemo {
public static void main(String[] args)throws Exception {
Resource res = new Resource();
SubThread st = new SubThread(res);
AddThread at = new AddThread(res);
new Thread(at, "加法线程 - A").start();
new Thread(at, "加法线程 - B").start();
new Thread(st, "减法线程 - X").start();
new Thread(st, "减法线程 - Y").start();
}
}
class Resource {
private int num = 0; // 这个要进行加减操作的数据
private boolean flag = true; // 加减的切换
// flag = true, 表示可以进行加法操作,但是无法进行减法操作
// flag = false, 表示可以进行减法操作,但是无法进行加法操作
public synchronized void add() throws Exception { // 执行加法操作
if (this.flag == false) { // 现在需要执行的是减法操作,加法操作要等待
this.wait();
}
Thread.sleep(100);
this.num ++;
System.out.println("【加法操作-" + Thread.currentThread().getName() + "】num = " + this.num);
this.flag = false; // 加法操作执行完毕,需要执行减法处理
this.notifyAll(); // 唤醒全部等待线程
}
public synchronized void sub() throws Exception{ // 执行减法操作
if (this.flag == true) { // 现在需要执行的是减法操作,加法操作要等待
this.wait();
}
Thread.sleep(200);
this.num --;
System.out.println("【减法操作-" + Thread.currentThread().getName() + "】num = " + this.num);
this.flag = true; // 减法操作执行完毕,需要执行加法处理
this.notifyAll();
}
}
class AddThread implements Runnable {
private Resource resource;
public AddThread(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int x = 0; x < 50; x++) {
try {
this.resource.add();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class SubThread implements Runnable {
private Resource resource;
public SubThread(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int x = 0; x < 50; x++) {
try {
this.resource.sub();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
心得:这是个典型的多线程案例,运用了生产者消费者模型,里面有线程的锁和同步问题,等待和唤醒问题,是一个典型的学习案例,运行正常的话,运行结果num 的值只会在0、1之间循环