1.同步代码块
public class Tickects1 implements Runnable{
//共享数据
private int ticket=100;
//创建锁对象
private Object obj=new Object();
public void run() {
while(true){
//同步代码块
synchronized(obj){
//可能会发生线程安全问题代码
if(ticket>0){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"售出了第"+ticket--+"张票");
}
}
}
}
}
public class Demo01 {
public static void main(String[] args) {
Tickects1 t=new Tickects1();
Thread t1=new Thread(t,"万达官方");
Thread t2=new Thread(t,"淘票票");
Thread t3=new Thread(t,"现场售票");
t1.start();
t2.start();
t3.start();
}
}
2.同步方法
public class Tickects2 implements Runnable{
//共享数据
private int ticket=100;
public void run() {
while(true){
sale();
}
}
//同步方法(内置锁对象this)
public synchronized void sale(){
if(ticket>0){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"售出了第"+ticket--+"张票");
}
}
}
public class Demo01 {
public static void main(String[] args) {
Tickects2 t=new Tickects2();
Thread t1=new Thread(t,"万达官方");
Thread t2=new Thread(t,"淘票票");
Thread t3=new Thread(t,"现场售票");
t1.start();
t2.start();
t3.start();
}
}
3.Lock接口
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Tickects3 implements Runnable{
//共享数据
private int ticket=100;
//Lock接口实现类对象
private Lock lock=new ReentrantLock();
public void run() {
while(true){
//获取锁
lock.lock();
if(ticket>0){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"售出了第"+ticket--+"张票");
}
//释放锁
lock.unlock();
}
}
}
public class Demo01 {
public static void main(String[] args) {
Tickects3 t=new Tickects3();
Thread t1=new Thread(t,"万达官方");
Thread t2=new Thread(t,"淘票票");
Thread t3=new Thread(t,"现场售票");
t1.start();
t2.start();
t3.start();
}
}