<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();
}
}