常用的两种方式,Thread 和Runnable
Thread 是一个类,它实现了Runnable 接口。

Runnable 是一个接口。

采用继承的方式实现多线程:
打印的结果:
Thread-1 卖票:ticket10
Thread-1 卖票:ticket9
Thread-1 卖票:ticket8
Thread-1 卖票:ticket7
Thread-1 卖票:ticket6
Thread-1 卖票:ticket5
Thread-1 卖票:ticket4
Thread-1 卖票:ticket3
Thread-1 卖票:ticket2
Thread-1 卖票:ticket1
Thread-0 卖票:ticket10
Thread-0 卖票:ticket9
Thread-0 卖票:ticket8
Thread-0 卖票:ticket7
Thread-0 卖票:ticket6
Thread-0 卖票:ticket5
Thread-0 卖票:ticket4
Thread-0 卖票:ticket3
Thread-0 卖票:ticket2
Thread-0 卖票:ticket1
Thread-2 卖票:ticket10
Thread-2 卖票:ticket9
Thread-2 卖票:ticket8
Thread-2 卖票:ticket7
Thread-2 卖票:ticket6
Thread-2 卖票:ticket5
Thread-2 卖票:ticket4
Thread-2 卖票:ticket3
Thread-2 卖票:ticket2
Thread-2 卖票:ticket1
2.采用实现接口的方式实现多线程:
打印结果:
Thread-0 卖票:ticket10
Thread-0 卖票:ticket9
Thread-0 卖票:ticket8
Thread-0 卖票:ticket7
Thread-0 卖票:ticket6
Thread-0 卖票:ticket5
Thread-0 卖票:ticket4
Thread-0 卖票:ticket3
Thread-0 卖票:ticket2
Thread-0 卖票:ticket1
Thread-1 卖票:ticket10
Thread-1 卖票:ticket9
Thread-1 卖票:ticket8
Thread-1 卖票:ticket7
Thread-1 卖票:ticket6
Thread-1 卖票:ticket5
Thread-1 卖票:ticket4
Thread-1 卖票:ticket3
Thread-1 卖票:ticket2
Thread-1 卖票:ticket1
Thread-2 卖票:ticket10
Thread-2 卖票:ticket9
Thread-2 卖票:ticket8
Thread-2 卖票:ticket7
Thread-2 卖票:ticket6
Thread-2 卖票:ticket5
Thread-2 卖票:ticket4
Thread-2 卖票:ticket3
Thread-2 卖票:ticket2
Thread-2 卖票:ticket1
根据面向对象的基础知识知道:单继承,多实现,所以实现Runnable 接口的方式更多的被使用。
本文详细对比了Java中Thread类与Runnable接口实现多线程的两种方式,通过实例演示了它们在打印结果上的不同,并强调了Runnable接口在面向对象设计中的优势。
&spm=1001.2101.3001.5002&articleId=121473270&d=1&t=3&u=115297c144d749d7bfed676a4d891963)
2137

被折叠的 条评论
为什么被折叠?



