創(chuàng)建線程2--實(shí)現(xiàn)Runnable接口

2019-07-07 23:44 更新

靜態(tài)代理

  1. 1.直接寫(xiě)的類(lèi)實(shí)現(xiàn)了Runnable相當(dāng)于真實(shí)角色You。
  2. 2.Thread相當(dāng)于靜態(tài)代理角色WeddingCompany。
  3. 3.Runnable相當(dāng)于Marry接口。
  1. /**
  2. *
  3. * 靜態(tài)代理 設(shè)計(jì)模式
  4. * 1.真實(shí)角色
  5. * 2.代理角色:持有真實(shí)角色的引用。
  6. * 3.二者實(shí)現(xiàn)相同的接口
  7. *
  8. */
  9. public class StaticProxy {
  10. public static void main(String[] args) {
  11. //創(chuàng)建真實(shí)角色
  12. Marry you = new You();
  13. //創(chuàng)建代理角色 + 真實(shí)角色的引用
  14. WeddingCompany weddingCompany = new WeddingCompany(you);
  15. //執(zhí)行任務(wù)
  16. weddingCompany.marry();
  17. }
  18. }
  19. //接口
  20. interface Marry{
  21. public abstract void marry();
  22. }
  23. //真實(shí)角色
  24. class You implements Marry{
  25. @Override
  26. public void marry() {
  27. // TODO Auto-generated method stub
  28. System.out.println("你和xxx結(jié)婚了!");
  29. }
  30. }
  31. //代理角色
  32. class WeddingCompany implements Marry{
  33. private Marry you;
  34. public WeddingCompany() {}
  35. public WeddingCompany(Marry you) {
  36. this.you = you;
  37. }
  38. private void before() {
  39. System.out.println("結(jié)婚之前的準(zhǔn)備工作。。。");
  40. }
  41. @Override
  42. public void marry() {
  43. // TODO Auto-generated method stub
  44. before();
  45. you.marry();
  46. after();
  47. }
  48. private void after() {
  49. System.out.println("結(jié)婚之后的收尾工作。。。");
  50. }
  51. }

使用實(shí)現(xiàn)Runnable接口的方式創(chuàng)建線程:

  1. public class MyThread implements Runnable {
  2. private int x = 30;
  3. @Override
  4. public void run() {
  5. // TODO Auto-generated method stub
  6. for(int i = 0; i < 10; i++) {
  7. try {
  8. Thread.sleep(500);
  9. } catch (InterruptedException e) {
  10. // TODO Auto-generated catch block
  11. e.printStackTrace();
  12. }
  13. synchronized(this) {
  14. System.out.println(Thread.currentThread().getName()+":x="+x);
  15. x--;
  16. }
  17. }
  18. }
  19. public static void main(String[] args) {
  20. //一個(gè)真實(shí)角色
  21. MyThread myThread = new MyThread();
  22. //三個(gè)代理角色
  23. new Thread(myThread, "a").start();
  24. new Thread(myThread, "b").start();
  25. new Thread(myThread, "c").start();
  26. //注意:可以有三個(gè)代理角色同時(shí)對(duì)一個(gè)對(duì)象代理,但有可能出錯(cuò),需要synchronized保持同步。
  27. }
  28. }

推薦使用實(shí)現(xiàn)Runnable接口的方式創(chuàng)建線程:

  1. 1.java是單繼承機(jī)制,但可以實(shí)現(xiàn)多個(gè)接口。
  2. 2.可以讓多個(gè)代理同時(shí)對(duì)一個(gè)對(duì)象操作。
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)