标签:while runnable 继承 sleep span getname 不能 private override
1 //代码演示: 2 public class Demo3 extends Thread{ 3 @Override 4 public void run() { 5 //run方法中要进行的操作 6 } 7 public static void main(String[] args) { 8 Demo3 demo3 = new Demo3(); 9 demo3.start(); 10 } 11 }
1 //代码演示: 2 //自定义类实现Runnable接口 3 public class ThreadDemo implements Runnable { 4 //创建线程的第一种方式:继承Thread类 5 private int ticket =100; 6 Object object = new Object(); 7 @Override 8 public void run() { 9 while(true) { 10 synchronized (object) { 11 if (ticket>0) { 12 try { 13 Thread.sleep(10); 14 } catch (Exception e) { 15 } 16 System.out.println(Thread.currentThread().getName()+"-----"+ticket--); 17 } 18 } 19 } 20 } 21 } 22 //执行类,三个线程同时执行,模拟一个买票的过程 23 public class Test { 24 public static void main(String[] args) { 25 ThreadDemo threadDemo = new ThreadDemo(); 26 Thread thread = new Thread(threadDemo); 27 Thread thread2 = new Thread(threadDemo); 28 Thread thread3 = new Thread(threadDemo); 29 thread.start(); 30 thread2.start(); 31 thread3.start(); 32 } 33 }
标签:while runnable 继承 sleep span getname 不能 private override
原文地址:http://www.cnblogs.com/anzhi/p/7465135.html