实现线程安全的三种方式
一、Synchronized
1. 同步方法
public class MyThread extends Thread{
private int ticket = 10000;
public void run(){
while (ticket > 0){
this.getTicket();
}
}
public synchronized void getTicket(){
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "--got ticket with no." + ticket);
ticket--;
}
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread);
Thread thread2 = new Thread(myThread);
Thread thread3 = new Thread(myThread);
thread1.setName("用户1");
thread2.setName("用户2");
thread3.setName("用户3");
thread1.start();
thread2.start();
thread3.start();
}
1. 同步代码块
public class MyThread2 extends Thread {
private int ticket = 10000;
public void run(){
while (ticket > 0) {
synchronized (this) {
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "--got ticket with no." + ticket);
ticket--;
} else {
break;
}
}
}
}
public static void main(String[] args) {
MyThread2 myThread2 = new MyThread2();
Thread thread1 = new Thread(myThread2);
Thread thread2 = new Thread(myThread2);
Thread thread3 = new Thread(myThread2);
thread1.setName("用户1");
thread2.setName("用户2");
thread3.setName("用户3");
thread1.start();
thread2.start();
thread3.start();
}
}
二、手动Lock
public class MyThread3 implements Runnable {
private int ticket = 100;
private ReentrantLock lock = new ReentrantLock(true);
@Override
public void run() {
while (ticket > 0) {
try {
lock.lock();
if (ticket > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "--got ticket with no." + ticket);
ticket--;
} else {
break;
}
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
MyThread3 myThread3 = new MyThread3();
Thread thread1 = new Thread(myThread3);
Thread thread2 = new Thread(myThread3);
Thread thread3 = new Thread(myThread3);
thread1.start();
thread2.start();
thread3.start();
}
}