数据竞争
车票售卖
package cn.bx.thread;
class TicketWindow implements Runnable {
private int count = 100;
public void run() {
while (true) {
if (count > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "售出车票,剩余车票:" + (--count));
} else {
break;
}
}
}
}
public class Ticket {
public static void main(String[] args) {
TicketWindow ticketWindow = new TicketWindow();
Thread one = new Thread(ticketWindow);
Thread two = new Thread(ticketWindow);
Thread three = new Thread(ticketWindow);
one.setName("1号窗口");
two.setName("2号窗口");
three.setName("3号窗口");
one.start();
two.start();
three.start();
}
}
会出现数据竞争
1号窗口售出车票,剩余车票:0
2号窗口售出车票,剩余车票:-1
3号窗口售出车票,剩余车票:-2
synchronized
class TicketWindow implements Runnable {
private int count = 100;
public void run() {
while (true) {
synchronized (this) {
if (count > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "售出车票,剩余车票:" + (--count));
} else {
break;
}
}
}
}
}
单例模式
package cn.bx.thread;
class Singleton {
private static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
if (instance==null){
synchronized (Singleton.class){
if (instance==null){
instance = new Singleton();
}
}
}
return instance;
}
}
public class SingletonNote {
public static void main(String[] args) {
Singleton foo = Singleton.getInstance();
Singleton bar = Singleton.getInstance();
System.out.println(foo ==bar);
}
}
Lock
class A {
private final ReentrantLock lock = new ReenTrantLock();
public void m() {
lock.lock();
try {
//保证线程安全的代码;
} finally {
}
}
}