解决线程不安全问题
*************************方式1
直接用
class *** implements Runnable{} + private static synchronized void *****(){}
解决
即实现Runnable 和用 同步方法
关于synchronized的理解
/**
* synchronized 一个线程在运行这个代码时 其他线程必须在外等待 等该线程完成时再执行
* 针对共享数据
* 解决线程不安全的问题
* 如果多个线程对同一个变量或者数据的时候使用
*/
/**
* @Author Lin
* @CreateTime 2021 04 2021/4/11 2:54
*/
public class WindowsTest1 {
public static void main(String[] args) {
Window1 w = new Window1();
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 Window1 implements Runnable {
private static int count = 100;
public void run() {
while (count >= 0) {
/**
* synchronized 一个线程在运行这个代码时 其他线程必须在外等待 等该线程完成时再执行
* 针对共享数据
* 解决线程不安全的问题
* 如果多个线程对同一个变量或者数据的时候使用
*/
show();
}
}
private static synchronized void show() {
if (count-- > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
System.out.println(Thread.currentThread().getName() + "购票成功,票号为:" + (count + 1));
}
}
}
*************************方式2
用public static ReentrantLock rl=new ReentrantLock(true);的方式解决
rl.lock()等于执行权 其他不能再执行必须等待
rl.unlock解锁 别的线程再执行
import java.util.concurrent.locks.ReentrantLock;
/**
* @Author Lin
* @CreateTime 2021 04 2021/4/11 2:54
*/
public class WindowsTest1 {
public static void main(String[] args) {
Window1 w = new Window1();
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 Window1 implements Runnable {
private static int count = 100;
//定义一个ReentrantLock 类
public static ReentrantLock rl=new ReentrantLock(true);
public void run() {
while (count >= 0) {
try {
//拿到锁
rl.lock();
show();
} catch (Exception e) {
e.printStackTrace();
} finally {
//执行完成后释放锁
rl.unlock();
}
}
}
private static void show() {
if (count-- > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
System.out.println(Thread.currentThread().getName() + "购票成功,票号为:" + (count + 1));
}
}
}