Runnable接口实现多线程
package Day23;
//多线称实现方式2()----Runnable【接口】
public class RunnableDemo implements Runnable {
//重写此接口的run方法
@Override
public void run() {
for(int x=0;x<100;x++){
//public static Thread currentThread()返回对当前正在执行的线程对象的引用---返回当前执行的线程对象
//获取当前线程对象的名称---Thread.currentThread.getName
System.out.println(Thread.currentThread().getName());
}
}
}
测试类
package Day23;
/*
* /*
* 方式2:实现Runnable接口
* 步骤:
* A:自定义类MyRunnable实现Runnable接口
* B:重写run()方法
* C:创建MyRunnable类的对象
* D:创建Thread类的对象,并把C步骤的对象作为构造参数传递
*/
public class RunnableTest {
public static void main(String[] args) {
//创建RunnableTest对象
RunnableDemo rbt = new RunnableDemo();
//public Thread(Runnable target,String name)分配新的 Thread 对象。
//target - 其 run 方法被调用的对象。
//name - 新线程的名称。
Thread td = new Thread( rbt,"大海");
Thread td1= new Thread(rbt,"长江");
//使线程开始执行---虚拟机调用此方法
td.start();
td1.start();
}
}
继承类Thread–实现卖电影票
package cn.itcast_06;
public class SellTicket extends Thread {
// 定义100张票
// private int tickets = 100;
// 为了让多个线程对象共享这100张票,我们其实应该用静态修饰
private static int tickets = 100;
@Override
public void run() {
// 定义100张票
// 每个线程进来都会走这里,这样的话,每个线程对象相当于买的是自己的那100张票,这不合理,所以应该定义到外面
// int tickets = 100;
// 是为了模拟一直有票
while (true) {
if (tickets > 0) {
System.out.println(getName() + "正在出售第" + (tickets--) + "张票");
}
}
}
}
package cn.itcast_06;
/*
* 某电影院目前正在上映贺岁大片(红高粱,少林寺传奇藏经阁),共有100张票,而它有3个售票窗口售票,请设计一个程序模拟该电影院售票。
* 继承Thread类来实现。
*/
public class SellTicketDemo {
public static void main(String[] args) {
// 创建三个线程对象
SellTicket st1 = new SellTicket();
SellTicket st2 = new SellTicket();
SellTicket st3 = new SellTicket();
// 给线程对象起名字
st1.setName("窗口1");
st2.setName("窗口2");
st3.setName("窗口3");
// 启动线程
st1.start();
st2.start();
st3.start();
}
}
利用Runnable接口实现电影票的售票
package Day23;
//使用Runnable接口实现电影票的销售----3个窗口
public class Movie implements Runnable {
//定义100张电影票
private int ticket =100;
//重写Runnable接口的run方法
@Override
public void run() {
while(true){
if (ticket>0){
//Runnable接口不能直接调用getName方法需要通过获取当前线程来获取名称
System.out.println(Thread.currentThread().getName()+"正在销售第"
+(ticket--)+"张电影票");
}
}
}
}
package Day23;
//实现Runnable接口的多线程
public class MovieDemo {
public static void main<