Thread 和 Runnable 区别 一分钟明白

来源:互联网 发布:python问卷系统源码 编辑:程序博客网 时间:2024/05/16 09:14
package com.thread;public class ThreadTicket {        static class MyThread1 extends Thread {          private int ticket = 5;            public void run() {        try {        while(this.ticket > 0) {                 Thread.sleep(1000);                    System.out.println(Thread.currentThread().getName()+"所选编号: " + this.ticket--);                  }} catch (Exception e) {e.printStackTrace();}                     }      };        static class MyThread2 implements Runnable {          private int ticket = 5;            public void run() {              try {            while (this.ticket > 0) {            System.out.println(Thread.currentThread().getName()+"所选编号: " + this.ticket--);                  }  } catch (Exception e) {e.printStackTrace();}        }      }        public static void main(String[] args) {          MyThread1 mt1 = new MyThread1();          MyThread1 mt2 = new MyThread1();          MyThread1 mt3 = new MyThread1();          mt1.setName("A");          mt2.setName("B");          mt3.setName("C");          mt1.start();        mt2.start();        mt3.start();    }            /**         每个线程都各卖了5张,共卖了15张票  但实际只有5张票,每个线程都卖自己的票  没有达到资源共享                    运行结果:      *       *  B所选编号: 5         B所选编号: 4         B所选编号: 3         B所选编号: 2         B所选编号: 1         A所选编号: 5         A所选编号: 4         A所选编号: 3         A所选编号: 2         A所选编号: 1         C所选编号: 5         C所选编号: 4         C所选编号: 3         C所选编号: 2         C所选编号: 1      */                  public static void main(String[] args) {          MyThread2 mt=new MyThread2();            new Thread(mt,"A").start();        new Thread(mt,"B").start();          new Thread(mt,"C").start();        }                  /**         达到了资源共享          运行结果:      *       *  A所选编号: 5         B所选编号: 4         B所选编号: 3         B所选编号: 2         C所选编号: 1     */}

0 0
原创粉丝点击