package com.tianmushanlu.thread; /** * 创建步骤: * 1. 自定义一个类实现Runnable接口。 * 2. 实现Runnable接口 的run方法,把自定义线程的任务定义在run方法上。 * 3. 创建Runnable实现类对象。 * 4. 创建Thread类 的对象,并且把Runnable实现类的对象作为实参传递。 * 5. 调用Thread对象 的start方法开启一个线程。 * * 注意: * Runnable实现类的对象并 不是一个线程对象,只不过是实现了Runnable接口的对象而已。 * 只有是Thread或者是Thread的子类才是线程对象。 * * @author zhangGB * */ class TicketWindows implements Runnable{ Integer num = 50; @Override public void run() { while(true) { synchronized ("锁对象") { if(num > 0) { System.out.println(Thread.currentThread().getName()+"售出了第"+num+"票"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } num--; }else{ System.out.println("票以售罄..........."); break; } } } } } public class ThreadDemo2 { public static void main(String[] args) { //创建了一个Runnable实现类的对象 TicketWindows TicketWindows = new TicketWindows(); Thread thread1 = new Thread(TicketWindows,"窗口1"); Thread thread2 = new Thread(TicketWindows,"窗口2"); Thread thread3 = new Thread(TicketWindows,"窗口3"); //开启3个线程售票 thread1.start(); thread2.start(); thread3.start(); } }
小海 2018-09-09
伍仔 2016-07-04
saya213 2013-05-19
伍仔 2016-07-15
白诗秀儿 2016-06-11
伍仔 2017-03-07
沙落雁 2017-03-07
白诗秀儿 2017-01-11
白诗秀儿 2016-03-23
沙落雁 2016-04-22
道友请留步 2025-03-26
道友请留步 2025-03-26
藏家708 2025-03-26
leoaim 2025-03-25
恭明惠 2025-03-26
藏家468 2025-03-26
藏家101 2025-03-25
藏家101 2025-03-25
藏家101 2025-03-25
藏家068 2025-03-25