通过Runnable接口实现多线程方法:
定义一个类,实现Runnable接口,重写run方法,通过Thread实例化,然后调用start方法启动线程。
案例如下:
/**
* 使用Runnable接口模拟4个售票窗口共同卖100张火车票的程序
*
* 共享数据,4个线程共同卖这100张火车票
* @author jiqinlin
*
*/
publicclass RunnableTest {
publicstaticvoid main(String[] args) {
Runnable runnable=new MyThread();
new Thread(runnable).start();
new Thread(runnable).start();
new Thread(runnable).start();
new Thread(runnable).start();
}
publicstaticclass MyThread implements Runnable{
//车票数量
privateint tickets=100;
publicvoid run() {
while(tickets>0){
System.out.println(Thread.currentThread().getName()+"卖出第 【"+tickets--+"】张火车票");
}
}
}
}