本帖最后由 王宝龙 于 2012-9-14 20:31 编辑
为什么要有两种创建线程的方式,一个Thread类不够吗??
这是第一种线程创建方式:- class Thr extends Thread
- {
- public void run()
- {
- for(int i=0;i<100;i++)
- {
- System.out.println(this.getName()+"~~~~~~~run"+i);
- }
- }
- }
- class ThreadDemo
- {
- public static void main(String[] arge)
- {
- Thr a = new Thr();
- Thr b = new Thr();
- a.start();
- b.start();
- for(int i=0;i<100;i++)
- {
- System.out.println("Hello World");
- }
- }
- }
复制代码 这是第二种:- <p>class Ticket implements Runnable//创建Ticket类并实现Runnable接口
- {
- public int ticket = 100;
- Object a = new Object();
- public void run()//实现Runnable接口的run()方法
- {
- while(true)
- {
- if(ticket>0)
- {
- System.out.println(Thread.currentThread().getName()+"~~~~~~"+ticket--);
- }
-
- }
- }
- }
- class TicketDemo
- {
- public static void main(String[] arge)
- {
-
- Ticket t = new Ticket();//创建Ticket类对象
- Thread a1 = new Thread(t);//将Ticket类对象作为参数传入Thread类对象
- Thread a2 = new Thread(t);
- Thread a3 = new Thread(t);
- a1.start();
- a2.start();
- a3.start();
- }
- }
- </p>
复制代码 |
|