在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Java多线程(一)Java多线程传统实现方法

2017-2-7 13:39| 发布者: zhangjf| 查看: 524| 评论: 0

摘要: Java多线程(一)Java多线程传统实现方法 Java多线程的传统实现方法有两种:一种是继承Thread类并重写其run方法;另一种是实现Runnable接口,实现其run方法。 /** * 多线程的传统实现方法 * */public class Tra ...
Java多线程(一)Java多线程传统实现方法

Java多线程的传统实现方法有两种:一种是继承Thread类并重写其run方法;另一种是实现Runnable接口,实现其run方法。

  1. /** * 多线程的传统实现方法 * */
  2. public class TraditionalThread {
  3. public static void main(String[] args) {
  4. /* * 方法1:覆盖父类Thread的run方法 */
  5. Thread thread = new Thread() {
  6. @Override
  7. public void run() {
  8. while(true) {
  9. try {
  10. Thread.sleep(500);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. System.out.println("输出1:" + Thread.currentThread().getName());
  15. System.out.println("输出2:" + this.getName());
  16. }
  17. }
  18. };
  19. thread.start();
  20. /* * 方法2:实现Runnable接口,实现其run方法 */
  21. Thread thread2 = new Thread(new Runnable() {
  22. @Override
  23. public void run() {
  24. while(true) {
  25. try {
  26. Thread.sleep(500);
  27. } catch (InterruptedException e) {
  28. e.printStackTrace();
  29. }
  30. System.out.println("输出1:" + Thread.currentThread().getName());
  31. // System.out.println("输出2:" + this.getName());
  32. }
  33. }
  34. });
  35. thread2.start();
  36. /* * 3:二者同时存在时的调用规则 * * 首先找子类的run方法, * 若子类没有覆盖run方法,则找Runnable的run方法(参考jdk中Thread.run()的实现) * 因此本代码会执行子类覆盖的run方法 */
  37. new Thread(new Runnable(){
  38. @Override
  39. public void run() {
  40. while(true) {
  41. try {
  42. Thread.sleep(500);
  43. } catch (InterruptedException e) {
  44. e.printStackTrace();
  45. }
  46. System.out.println("Runnable:" + Thread.currentThread().getName());
  47. }
  48. }
  49. }){
  50. @Override
  51. public void run() {
  52. while(true) {
  53. try {
  54. Thread.sleep(500);
  55. } catch (InterruptedException e) {
  56. e.printStackTrace();
  57. }
  58. System.out.println("Thread:" + Thread.currentThread().getName());
  59. }
  60. }
  61. }.start();
  62. }
  63. }
复制代码

来自: http://blog.csdn.net//kingzone_2008/article/details/44571181

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-9 08:28

Copyright 2015-2025 djqfx

返回顶部