本文主要是介绍Runnable接口创建多线程例子,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
哈尔滨火车站下面有三个火车票代售点,假如哈尔滨到北京的火车票总共是200张,如何用程序来实现三个售票点同时卖票的功能。
public class Ticket implements Runnable{private int tickets = 200; //200张火车票boolean flag = true;private synchronized void sale() {if (tickets <= 0) {flag = false;return;}tickets--;System.out.print(Thread.currentThread().getName() + " sales a ticket, ");if (tickets > 1) System.out.println("there are " + tickets + " tickets");else System.out.println("there is " + tickets + " ticket");}public void run() {while(flag){sale();try {Thread.sleep(100);}catch (InterruptedException e){e.printStackTrace();}}}
}
public class Main {public static void main(String[] args) {Ticket t = new Ticket();Thread th1 = new Thread(t,"system 1");Thread th2 = new Thread(t,"system 2");Thread th3 = new Thread(t,"system 3");th1.start();th2.start();th3.start();}
}
这篇关于Runnable接口创建多线程例子的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!