数据竞争

车票售卖

  1. package cn.bx.thread;
  2. class TicketWindow implements Runnable {
  3. private int count = 100;
  4. public void run() {
  5. while (true) {
  6. if (count > 0) {
  7. try {
  8. Thread.sleep(10);
  9. } catch (InterruptedException e) {
  10. e.printStackTrace();
  11. }
  12. System.out.println(Thread.currentThread().getName() + "售出车票,剩余车票:" + (--count));
  13. } else {
  14. break;
  15. }
  16. }
  17. }
  18. }
  19. public class Ticket {
  20. public static void main(String[] args) {
  21. TicketWindow ticketWindow = new TicketWindow();
  22. Thread one = new Thread(ticketWindow);
  23. Thread two = new Thread(ticketWindow);
  24. Thread three = new Thread(ticketWindow);
  25. one.setName("1号窗口");
  26. two.setName("2号窗口");
  27. three.setName("3号窗口");
  28. one.start();
  29. two.start();
  30. three.start();
  31. }
  32. }

会出现数据竞争

  1. 1号窗口售出车票,剩余车票:0
  2. 2号窗口售出车票,剩余车票:-1
  3. 3号窗口售出车票,剩余车票:-2

synchronized

  1. class TicketWindow implements Runnable {
  2. private int count = 100;
  3. public void run() {
  4. while (true) {
  5. synchronized (this) {
  6. if (count > 0) {
  7. try {
  8. Thread.sleep(10);
  9. } catch (InterruptedException e) {
  10. e.printStackTrace();
  11. }
  12. System.out.println(Thread.currentThread().getName() + "售出车票,剩余车票:" + (--count));
  13. } else {
  14. break;
  15. }
  16. }
  17. }
  18. }
  19. }

单例模式

  1. package cn.bx.thread;
  2. class Singleton {
  3. private static Singleton instance = null;
  4. private Singleton(){}
  5. public static Singleton getInstance(){
  6. if (instance==null){
  7. synchronized (Singleton.class){
  8. if (instance==null){
  9. instance = new Singleton();
  10. }
  11. }
  12. }
  13. return instance;
  14. }
  15. }
  16. public class SingletonNote {
  17. public static void main(String[] args) {
  18. Singleton foo = Singleton.getInstance();
  19. Singleton bar = Singleton.getInstance();
  20. System.out.println(foo ==bar);
  21. }
  22. }

Lock

  1. class A {
  2. private final ReentrantLock lock = new ReenTrantLock();
  3. public void m() {
  4. lock.lock();
  5. try {
  6. //保证线程安全的代码;
  7. } finally {
  8. }
  9. }
  10. }