标签:sys func art 同步方法 方式 问题 port override fun
package com.synchronized1; // 买票示例 // 使用同步代码块解决线程安全问题 public class TicketRunnableImp implements Runnable { private int ticket = 100; Object o=new Object(); @Override public void run() { while (true) { synchronized (o){ if (ticket > 0) { System.out.println(Thread.currentThread().getName() + "-->正在售第"+ticket+"张票!"); ticket--; } } } } }
package com.synchronized2; // 买票示例 // 使用同步方法解决线程安全问题 public class TicketRunnableImp implements Runnable { private int ticket = 100; Object o = new Object(); @Override public void run() { while (true) { func(); } } // 同步方法的锁对象是调用者对象(Runnable对象) public synchronized void func(){ if (ticket > 0) { System.out.println(Thread.currentThread().getName() + "-->正在售第" + ticket + "张票!"); ticket--; } } }
package com.staticSyn; // 买票示例 // 使用同步方法解决线程安全问题 public class TicketRunnableImp implements Runnable { private static int ticket = 100; Object o = new Object(); @Override public void run() { while (true) { func(); } } // 静态方法的锁对象是本类的class属性 public synchronized static void func(){ if (ticket > 0) { System.out.println(Thread.currentThread().getName() + "-->正在售第" + ticket + "张票!"); ticket--; } } }
package com.lock1; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; // 买票示例 // 使用同步代码块解决线程安全问题 public class TicketRunnableImp implements Runnable { private int ticket = 100; Object o = new Object(); Lock lock=new ReentrantLock(); @Override public void run() { while (true) { lock.lock(); if (ticket > 0) { System.out.println(Thread.currentThread().getName() + "-->正在售第" + ticket + "张票!"); ticket--; } lock.unlock(); } } }
package com.lock2; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; // 买票示例 // 使用同步代码块解决线程安全问题 public class TicketRunnableImp implements Runnable { private int ticket = 100; Object o = new Object(); Lock lock = new ReentrantLock(); @Override public void run() { while (true) { lock.lock(); try { if (ticket > 0) { System.out.println(Thread.currentThread().getName() + "-->正在售第" + ticket + "张票!"); ticket--; } } catch (Exception e) { System.out.println(e); } finally { lock.unlock(); } } } }
package com.lock2; public class DemoTicket { public static void main(String[] args) { TicketRunnableImp t=new TicketRunnableImp(); Thread t1=new Thread(t); Thread t2=new Thread(t); Thread t3=new Thread(t); t1.start(); t2.start(); t3.start(); } }
标签:sys func art 同步方法 方式 问题 port override fun
原文地址:https://www.cnblogs.com/sun-10387834/p/12872882.html