본문 바로가기

컴퓨터/IT

자바 리스너 기본

자바에서 클래스의 행동을 다른클래스에 알려주는 방법이다.
잘만 구현하면 좋은 프로그램을 만들수있겠다~~ ^0^





[Test.java]
interface Listener
{
    public void  startListener(String log);
    public void runListener(String log);
}

class Test2 implements Listener {
    public synchronized void startListener(String log) {
     System.out.println("Bclass started:"+log);
    }
    public synchronized void runListener(String log) {
     System.out.println("Bclass running:"+log);
    }
   
    Test2() {
     Bclass myb  =  new Bclass(this);
     Thread thread = new Thread(myb);
     thread.start();
    }
    public static void main(String[] args) {
         Test2 t2 = new Test2();
    }
}

----------------------------------------------------------------------------
[Bclass.java]

public class Bclass implements Runnable{
 private Listener listener;
 private int i = 0;
 
    Bclass(Listener l) {
       this.listener = l;
       this.listener.startListener ("메롱이당 ㅋㅋㅋ 요이땅~~~");  
    }
   
    public void run() {
     while (true) {
      this.i++;
      try{Thread.sleep(10);}catch (Exception e) {}
      this.listener.runListener(i+"--나지금 돌고 있니~ ㅋㅋㅋㅋ");
     }
    }
   
}