This article introduces two shackles for multi-threading implementation of multiple window ticketing problems, namely synchronized, lock() and unlock()
The specific code is as follows:
The first type:
package Runnable; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /* * Synchronization* There are two ways to lock* here: * 1.synchronized * 2.lock() and unlock() */ public class MyRunnable implements Runnable { private int tickets = 100; // Define lock private Lock lock = new ReentrantLock(); public void run() { while (true) { // Lock 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() + "Sold" + (tickets--) + "Tickets"); } lock.unlock(); } } }result:
The second type:
package Runnable; /* * Synchronized* There are two ways to lock* here: * 1.synchronized * 2.lock() and 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() + "Sold" + (tickets--) + "Tickets"); } } } } }result:
package Runnable; public class RunnableDemo { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread t1 = new Thread(myRunnable, "Window One"); Thread t2 = new Thread(myRunnable, "Window Two"); Thread t3 = new Thread(myRunnable, "Window Three"); t1.start(); t2.start(); t3.start(); } }I don’t know if it was a coincidence or something, but when I was running these two multi-threaded small instances, the computer suddenly got stuck and I quickly turned off eclipse.
There are statements about ending the process and have not been added, please refer to it yourself.
The above is the entire content of this article about the Java multi-threaded window ticketing problem example. I hope it will be helpful to the crackdown. If you have any questions, please leave a message at any time and look forward to your valuable comments.