本文介紹了多線程實現多個窗口售票問題的兩種枷鎖方式, 分別是synchronized 和lock()和unlock()
具體代碼如下:
第一種:
package Runnable; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /* * 同步* 這裡有兩種方式加鎖* 分別是* 1.synchronized * 2.lock()和unlock() */ public class MyRunnable implements Runnable { private int tickets = 100; // 定義鎖private Lock lock = new ReentrantLock(); public void run() { while (true) { // 加鎖lock.lock(); if (tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "售出了第" + (tickets--) + "張票"); } lock.unlock(); } } }結果:
第二種:
package Runnable; /* * 同步* 這裡有兩種方式加鎖* 分別是* 1.synchronized * 2.lock()和unlock() */ public class MyRunnable implements Runnable { private int tickets = 100; public void run() { while (true) { synchronized (this) { if (tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "售出了第" + (tickets--) + "張票"); } } } } }結果:
package Runnable; public class RunnableDemo { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread t1 = new Thread(myRunnable, "窗口一"); Thread t2 = new Thread(myRunnable, "窗口二"); Thread t3 = new Thread(myRunnable, "窗口三"); t1.start(); t2.start(); t3.start(); } }不知道是巧合還是怎麼回事,運行這兩個多線程小實例的時候,電腦突然卡了起來,我趕緊把eclipse關了。
有關於結束進程的語句並沒有添加,自行參閱吧。
以上就是本文關於Java多線程窗口售票問題實例的全部內容,希望對打擊有所幫助。如有問題可以隨時留言,期待您的寶貴意見。