解决线程安全的三种方式
方法一: 同步代码块-----锁对象可以是任意对象
synchronized ( 锁对象 ) {
你需要的逻辑
}
public class sellTicket1 implements Runnable {
int ticket = 100;
public static final Object lock = new Object();
@Override
public void run() {
while (true) {
synchronized (lock) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "卖出了第" + ticket + "张票");
ticket--;
}
}
}
}
}
class TextTicket1 {
public static void main(String[] args) {
sellTicket1 truck = new sellTicket1();
Thread thread = new Thread(truck, "窗口一");
Thread thread1 = new Thread(truck, "窗口二");
Thread thread2 = new Thread(truck, "窗口三");
thread.start();
thread1.start();
thread2.start();
}
}
方法二: 同步方法-----锁对象时this,即本类对象
修饰符 synchronized 返回值类型 方法名(方法参数)
{
需要同步执行的代码
}
public class sellTicket2 implements Runnable{
int ticket = 100;
@Override
public void run() {
while (true) {
sellTickets();
}
}
public synchronized void sellTickets(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "卖出了第" + ticket + "张票");
ticket--;
}
}
}
class TextTicket2 {
public static void main(String[] args) {
sellTicket2 truck = new sellTicket2();
Thread thread = new Thread(truck, "窗口一");
Thread thread1 = new Thread(truck, "窗口二");
Thread thread2 = new Thread(truck, "窗口三");
thread.start();
thread1.start();
thread2.start();
}
方法三:------lock锁(锁对象是Lock接口对象)
Lock lock = new ReentrantLock();
public class sellTicket3 implements Runnable{
int ticket = 100;
Lock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
lock.lock();
if (ticket > 0) {
try {
Thread.sleep(100);
System.out.println(Thread.currentThread().getName() + "卖出了第" + ticket + "张票");
ticket--;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
}
class TextTicket3 {
public static void main(String[] args) {
sellTicket3 truck = new sellTicket3();
Thread thread = new Thread(truck, "窗口一");
Thread thread1 = new Thread(truck, "窗口二");
Thread thread2 = new Thread(truck, "窗口三");
thread.start();
thread1.start();
thread2.start();
}
}