Thread(需求:简单卖票程序 extends Thread;implements Runnable)

<pre name="code" class="java">package process;
/*
 * 多线程:
 * 需求:简单卖票程序
 * 多个窗口同时卖票
 * 
 * 解决:四个窗口共享100张票 1,2
 */
//=========================可以==============================================================
class Ticket extends Thread{
	private static int tick = 100;//1,static 一般不试用,生命周期太长;
	
	private int x = 0;
	public void run(){
		while(true){
			if(tick > 0){
				System.out.println(x++ +"号   "+Thread.currentThread().getName() +"sale:" + tick--);
			}
		}
	}
}
public class ThreadDemo4 {

	public static void main(String[] args){
		Ticket t = new Ticket();
		Ticket t1 = new Ticket();
		Ticket t2 = new Ticket();
		Ticket t3 = new Ticket();
		t.start();
		t1.start();
		t2.start();
		t3.start();
		//,2,已经运行的线程不能再开启;没有意义;java.lang.IllegalThreadStateException
		
	}
}

 


</pre><pre name="code" class="java"><pre name="code" class="java">
</pre><pre name="code" class="java"><pre name="code" class="java">package process;

/*
 * 创建线程的第二种方式:实现runnable接口
 * 
 * 步骤:
 * 1,定义类实现Runnable接口
 * 2,覆盖接口中的run方法
 * 3,通过thread的类建立线程对象
 * 4,将runnable接口的子类作为实际参数传递给thread类的构造函数
 * 	为什么药将runnable接口的子类对象 传递给 thread类的构造函数
 * 	因为,自定义run方法所属的对象是runnable结构的子对象;
 * 	所以要让线程去指定对象的run方法,就必须明确改run方法所属对象;
 * 5,调用thread类的start(),并调用runnable子类的run();
 * 
 * 继承 thread 和 实现runnable的区别;
 * 
 * 实现好处:避免了单继承的局限性;
 * 在定义线程时,建议使用实现方式;
 * 
 * 两种方式的区别:
 * 继承 thread,线程代码存放thread子类run方法中
 * 实现runnable:线程代码存放在接口的子类的run方法中;
 */
class Tickets implements Runnable{
	
	private int tick = 100;
	@Override
	public void run() {
		int i = 0;
		while(true){
			if(tick > 0){
				System.out.println(i++ + " 号" + Thread.currentThread().getName() + "sale: " + tick--);
			}
		}
	}
}

public class ThreadDemo5 {

	public static void main(String[] args){
		
		Tickets t = new Tickets();
		
		Thread t1 = new Thread(t);
		Thread t2 = new Thread(t);
		Thread t3 = new Thread(t);
		Thread t4 = new Thread(t);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		
	}
}


 

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值