Runnable与火车购票系统


火车购票系统

package homework;
class SellTick extends Thread{
    private static int ticks=100;//这用的static三个进程处理一个事件也可以runnable
    private static int num;
    SellTick(String name){
        super(name);
    }
    @Override
    public void run(){
        ticks--;
       while(true){
           if(ticks>0){
               System.out.println(getName()+"票号:"+ticks);
               ticks--;
               num++;
           }
           else{
               break;
           }

       }
    }

    public static int getNum() {
        return num;
    }
}

public class test2 {
    public int num=0;
    public static void main(String[] args) {

        var w1=new SellTick("窗口1");
        var w2=new SellTick("窗口2");
        var w3=new SellTick("窗口3");
        w1.start();
        w2.start();
        w3.start();
    }
}

————————————————————————————————————————————————
Runable:

为什么可以共用runable的对象因为,

package homework;
class Mthread implements Runnable{
    public void run(){
        for(int i=0;i<100;i++){
            if(i%2==0){
                System.out.println(i);
            }
        }
    }
}

public class test3 {
    public static void main(String[] args) {
        Mthread mthread = new Mthread();//Runnable的实例化
        Thread thread1 = new Thread(mthread);
        thread1.start();//Thread  1.可以调用,二可以调用当前线程的run()
        Thread tread2 = new Thread(mthread);//共用了mthread但是创建了两个进程,两个进程执行同应该对象的方法
        tread2.start();
    }
}

两种进程创建一中是直接用Thread一种是接口Runnable
Runnable方法更加好
首先有共享数据的时候用Runnable
和Runnable是接口形式如果要继承其他类Thread占用了继承,因为单继承
共享数据 new Thread()
new Thread()