java thread implements Runnable implementation

package com.tianmushanlu.thread;
/**
 * Creation steps:
 * 1. Customize a class to implement the Runnable interface.	
 * 2. Implement the run method of the Runnable interface, and define the tasks of the custom thread on the run method.
 * 3. Create a Runnable implementation class object.
 * 4. Create an object of the Thread class and pass the object of the Runnable implementation class as an argument.
 * 5. Call the start method of the Thread object to start a thread.
 *
 * Notice:
 * The object of the Runnable implementation class is not a thread object, but an object that implements the Runnable interface.
 * Only Thread or a subclass of Thread is a thread object.
 *
 *
 *
 */
class TicketWindows implements Runnable{

	Integer num = 50;
	@Override
	public void run() {
		while(true) {
			synchronized ("lock object") {
				if(num > 0) {
					System.out.println(Thread.currentThread().getName()+"sold "+num+" ticket");
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace ();
					}
					on one--;
				}else{
					System.out.println("Tickets are sold out........");
					break;
				}
			}	
		}
		
	}
	
}


public class ThreadDemo2 {
	public static void main(String[] args) {
		//Create an object of the Runnable implementation class
		TicketWindows TicketWindows = new TicketWindows();
		Thread thread1 = new Thread(TicketWindows,"窗口1");
		Thread thread2 = new Thread(TicketWindows,"窗口2");
		Thread thread3 = new Thread(TicketWindows,"窗口3");
		//Open 3 threads to sell tickets
		thread1.start();
		thread2.start();
		thread3.start();
	}
	

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327105813&siteId=291194637