实现 Runnable 的同步方法
- package synchronization.method;
- /*
- 用同步方法解决实现 Runnable 的安全问题
- @author zsben
- @create 2020-01-03 13:48
- */
- class WindowRun implements Runnable{
- private int ticket = 100;
- @Override
- public void run() {
- while (true) {
- show();
- }
- }
- private synchronized void show(){// 用的那把锁就是 this
- if (ticket> 0) {
- System.out.println(Thread.currentThread().getName() + ":" + ticket);
- ticket--;
- }
- }
- }
- public class WindowRunnableTest {
- public static void main(String[] args) {
- WindowRun windowRun = new WindowRun();
- Thread t1 = new Thread(windowRun);
- Thread t2 = new Thread(windowRun);
- Thread t3 = new Thread(windowRun);
- t1.start();
- t2.start();
- t3.start();
- }
- }
继承 Thread 的同步方法
- package synchronization.method;
- /*
- 创建三个窗口买票, 总票数为 100 张
- 同步方法解决总结:
- 1. 同步方法仍然需要同步锁, 只是不需要显示声明
- 2. 非静态 (实现 Runnable) 的同步方法: 同步监视器是 this
- 静态 (继承 Thread 类) 的同步方法: 同步监视器是当前类本身
- @author zsben
- @create 2020-01-03 12:41
- */
- class Windows extends Thread{
- private static int ticket = 100;
- @Override
- public void run() {
- while(true) {
- show();
- }
- }
- private static synchronized void show(){// 同步监视器就是 Windows.class
- try {
- sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- if (ticket> 0) {
- System.out.println(Thread.currentThread().getName() + ":" + ticket);
- ticket--;
- }
- }
- }
- public class WindowThreadTest {
- public static void main(String[] args) {
- Windows t1 = new Windows();
- Windows t2 = new Windows();
- Windows t3 = new Windows();
- t1.setName("窗口 1");
- t2.setName("窗口 2");
- t3.setName("窗口 3");
- t1.start();
- t2.start();
- t3.start();
- }
- }
来源: http://www.bubuko.com/infodetail-3364792.html