目录
一、synchronized同步代码块
/**
*
*/
package com.threadsafe;
/**
* 线程安全(不推荐):synchronized同步代码块
* @author yyx
* 2021年3月3日
*/
public class ThreadSafe {
public static void main(String[] args) {
Window w = new Window();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
class Window implements Runnable {
int ticket = 20;// 共享数据
public void run() {
while (true) {
// this表示当前对象,本题中即为w
synchronized (this) {
if (ticket > 0) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "售票,票号为:" + ticket--);
}
}
}
}
}
二、synchronized同步方法
/**
*
*/
package com.threadsafe;
/**
* 线程安全(不推荐):synchronized同步方法
* @author yyx
* 2021年3月3日
*/
public class ThreadSafe {
public static void main(String[] args) {
Window w = new Window();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
class Window implements Runnable {
int ticket = 20;// 共享数据
public void run() {
while (true) {
show();
}
}
public synchronized void show() {
if (ticket > 0) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "售票,票号为:" + ticket--);
}
}
}
三、reentrantLock可重入锁
/**
*
*/
package com.threadsafe;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 线程安全(推荐):ReentrantLock可重入锁
* @author yyx
* 2021年3月3日
*/
public class ThreadSafe {
public static void main(String[] args) {
Window w = new Window();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
class Window implements Runnable {
int ticket = 20;// 共享数据
Lock lock = new ReentrantLock();
public void run() {
while (true) {
lock.lock(); // 获取锁
try {
if (ticket > 0) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "售票,票号为:" + ticket--);
}
} finally {
lock.unlock(); // 释放锁
}
}
}
}