java 多线程Thread与Runnable的区别

1.Runnable适合多线程操作同一资源。

2.Runnable接口可以避免java单继承带来的局限

3.Runnable增强代码健壮性,代码被多个线程共享

测试:

[java] view plain copy

  1. package main.uitls;

  2. publicclass Demo {

  3. publicstaticvoid main(String[] arg0){

  4. Mythread m1 = new Mythread();

  5. Mythread m2 = new Mythread();

  6. Mythread m3 = new Mythread();

  7. m1.start();

  8. m2.start();

  9. m3.start();

  10. /*MyRunnable myRunnable =new MyRunnable();

  11. Thread m1 = new Thread(myRunnable);

  12. Thread m2 = new Thread(myRunnable);

  13. Thread m3 = new Thread(myRunnable);

  14. m1.start();

  15. m2.start();

  16. m3.start();*/

  17. }

  18. }

  19. class Mythread extends Thread{

  20. publicint num = 5;

  21. publicvoid run() {

  22. for(int i=100;i > 0;i--){

  23. if(num>0){

  24. System.out.println("当前剩余票数:"+num--);

  25. }

  26. }

  27. }

  28. }

  29. class MyRunnable implements Runnable{

  30. publicint num = 5;

  31. publicvoid run() {

  32. for(int i=100;i > 0;i--){

  33. if(num>0){

  34. System.out.println("当前剩余票数:"+num--);

  35. }

  36. }

  37. }

  38. }

当使用Thread时,多个线程之间数据没有共享,返回的结果为(每次运行结果可能不同)

[html] view plain copy

  1. 当前剩余票数:5

  2. 当前剩余票数:4

  3. 当前剩余票数:3

  4. 当前剩余票数:5

  5. 当前剩余票数:2

  6. 当前剩余票数:5

  7. 当前剩余票数:1

  8. 当前剩余票数:4

  9. 当前剩余票数:3

  10. 当前剩余票数:2

  11. 当前剩余票数:4

  12. 当前剩余票数:1

  13. 当前剩余票数:3

  14. 当前剩余票数:2

  15. 当前剩余票数:1

当使用Runnable时县城之间数据共享:

[java] view plain copy

  1. MyRunnable myRunnable =new MyRunnable();

  2. Thread m1 = new Thread(myRunnable);

  3. Thread m2 = new Thread(myRunnable);

  4. Thread m3 = new Thread(myRunnable);

  5. m1.start();

  6. m2.start();

  7. m3.start();

结果为:

[html] view plain copy

  1. 当前剩余票数:5

  2. 当前剩余票数:3

  3. 当前剩余票数:4

  4. 当前剩余票数:1

  5. 当前剩余票数:2


分享到:


相關文章: