java-多线程-继承THREAD卖票

一、继承Thread
  1一直有个问题
     当我把调用方式换成下述不是也能实现卖票吗?
package Thread;
public class MyThreadTest extends Thread {

     private  int ticket=20;
   
   public void run() {
       while(true) {
           synchronized (this) {
               try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
             if(ticket>0) {
               System.out.println(Thread.currentThread().getName() + "..." + ticket--);              
           }    else {
               break;
           }
          }        
       }     
   }
   public static void main(String[] args) {
       MyThreadTest myThreadTest1 = new MyThreadTest();
//       MyThreadTest myThreadTest2 = new MyThreadTest();
//       MyThreadTest myThreadTest3 = new MyThreadTest();
//       myThreadTest1.start();
//       myThreadTest2.start();
//       myThreadTest3.start();

//调用方式 Thread t1 = new Thread(myThreadTest1, "窗口1"); Thread t2 = new Thread(myThreadTest1, "窗口2"); t1.start(); t2.start(); } }

二、实现runnable接口
package Thread;

public class MyRunnableTest implements Runnable {
    private int ticket = 20;
    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                try {
                    Thread.sleep(100);  //更好的体现结果
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + "......" + ticket--);
                }
            }
        }
    }
}

class RunnableStart {
    public static void main(String[] args) {
        MyRunnableTest myRunnableTest = new MyRunnableTest();
        Thread t1 = new Thread(myRunnableTest, "窗口1");
        Thread t2 = new Thread(myRunnableTest, "窗口2");
        t1.start();
        t2.start();
    }
}
 
    

 

 

 

转载于:https://www.cnblogs.com/yugong/p/9225162.html

你可能感兴趣的:(java-多线程-继承THREAD卖票)