1. 쓰레드의 생성

 1) 쓰레드를 사용할려면 Thread를 상속받아 run()를 오버라이드하고 실행은 start()로 한다.

 2) run() 할 메소드에 Runnable 인터페이스를 상속받아 run()을 구현하고, 실행하는 곳에서는 start()를 하지 못하기 때문에 Thread를 생성해야 한다. Thread t1 = new Thread(runnable 인터페이스를 상속받은 클래스);


2. 쓰레드의 종료

 1) run() 내부의 작업을 반복문으로 만들어 조건으로 종료를 시킬 수 있다.

 2) exception(예외처리) 으로 해결하는 방법.

  -  시작한 곳에서 종료시 interrupt(); 명령으로 인터럽트를 발생시키면 종료된다.

 try{

while(!Thread.currentThread().isInterrupted()){

System.out.println("I'm alive..."+a);

Thread.sleep(10);

a++;

}

}catch(InterruptedException e){

}finally{

System.out.println("I'm dead....");

}


3. 쓰레드 관리

 1) sleep

 2) stop

 3) wait // synchronized()

'Programming > JAVA' 카테고리의 다른 글

JDBC 설정  (2) 2011.03.24
JAVA IO  (1) 2011.03.24
Java Call by value, Call by reference  (2) 2011.03.24
The AWT Component Library  (1) 2011.03.24
The AWT Event Model  (0) 2011.03.24

 

http://trypsr.tistory.com/74

에서 아주 잘 정리하셨길래 퍼왔음.

 

테스트 없이 눈으로만 코딩할 때 가장  쉬운 부분이 call by value 와 call by refence 를  이해하지 못할 때 생기는 오류가 아닐까 싶다.

기본형과 객체가  기본형은 call by value 이고 객체는 call by refence 라는  대부분의 java 개발자들이 알고 있을꺼라 생각한다.

그 예로 swap  가장 많이 설명하는데..

예제 1) 

class Test {
    private static void swap(int a, int b) {
        int temp = a;
        a = b;
        b = temp;
    }

    public static void main(String args[]) {
        int a = 1;
        int b = 2;

        System.out.println("a => " + a);
        System.out.println("b => " + b);

        swap(a, b);

        System.out.println("------- swap 후 -------");

        System.out.println("a => " + a);
        System.out.println("b => " + b);
    }
}

예제 1 의  원하던 결과가 아닌 것을 바로 알아 낼 수 있을 것이다.
 메소드에 넘기는 것은 reference 가 아닌 value 이기 때문에...
쉽다.  

다음 예제 2 를 보자
예제 2)

class Test {
    private static void swap(Integer a, Integer b) {
        Integer temp = a;
        a = b;
        b = temp;
    }

    public static void main(String args[]) {
        Integer a = new Integer(1);
        Integer b = new Integer(2);

        System.out.println("a => " + a.intValue());
        System.out.println("b => " + b.intValue());

        swap(a, b);

        System.out.println("------- swap 후 -------");

        System.out.println("a => " + a.intValue());
        System.out.println("b => " + b.intValue());
    }
}

예제 2  경우 Integer 는 Object 이다. Object 는 call by reference  
따라서 위의 예제는 원하는 결과를 가져올 것이다.
그러나 실행을 하면 예제 1과 전혀 다르지 않다는 것을 알  있다.

왜? 객체는 call by reference 라며 사기친거야?

 말하면 객체는 call by reference 맞다

그러나 해당 객체를  새로운 reference 를 참조해서 넘기는 것이다.

따라서 동일한 객체를  있지만 
main 에서의 reference 값과 swap 함수에서의 reference 값은  

따라서 위의 예제의 경우 원하는 결과가 나오지 않는다.

  이부분이 가장 이해가 힘들었는데, 즉 메소드에서 변수의 주소를 받았다 하더라도 실제 메소드 안에서 실행될때는 지역변수일 뿐입니다. 즉, 메소드를 벗어나게 되면 영향력이 없어지는 것이죠..

그래서 영향력이 있을때인 메소드 안에서 직접 그 주소의 값을 변경하면 영향을 받지만, 그런것이 아닌 단순한 주소의 복사는, 그 메소드 안에있는 지역변수의 변화일 뿐 실제 값에는 영향이 없습니다.


 어떻게 해야 해?

예제 3 을 보자.

예제 3)

class Test {
    int value;

    Test(int value) {
        this.value = value;
    }

    private static void swap(Test a, Test b) {
        int temp = a.value;
        a.value = b.value;
        b.value = temp;
    }

    public static void main(String args[]) {
        Test a = new Test(1);
        Test b = new Test(2);

        System.out.println("a => " + a.value);
        System.out.println("b => " + b.value);

        swap(a, b);

        System.out.println("------- swap 후 -------");

        System.out.println("a => " + a.value);
        System.out.println("b => " + b.value);
    }
}

예제 2와 같이 객체의 reference 를 넘긴다.
reference 를 직접  게 아니라.
reference 가 참조하는 객체의 value 를 변경하고 있다.
 같은 객체를 보고 있는 main 에서도 값이 바뀌는 것을 알  있다.

call by reference

해당 객체의 주소값을 직접 넘기는 게 아닌 객체를 보는 또 다른 주소값을 만들어서 넘기다는 사실을 잊지 말자~

 

'Programming > JAVA' 카테고리의 다른 글

JAVA IO  (1) 2011.03.24
JAVA Threads  (2) 2011.03.24
The AWT Component Library  (1) 2011.03.24
The AWT Event Model  (0) 2011.03.24
Building GUIs & Java Graphics  (0) 2011.03.24

1. Button class

2. Label class

3. checkbox class

4. checkboxgroup class : Radio button

5. choice

6. List

7. TextComponent

8. TextField

9. TextArea

10. Scrollbar

11. Canvas class

12. ScrollPane class

13. Dialog Class

 1) Modeless / modal : 다이얼로그가 해결 되어야 다른 작업이 가능.

14. FileDialog class

 1) fdOpen.setVisible(true);

     System.out.println("경로 ="+fdOpen.getDirectory()+fdOpen.getFile());

15. Menu

 

 

 

 

ps----------------------------------------------------------

1. 인터페이스를 상속받으면 모든 메소드를 오버라이딩해야한다.

하지만 이미 이 인터페이스를 상속받은 클래스를 상속한다면, 원하는 메소드만 오버라이딩 할 수 있다.

'Programming > JAVA' 카테고리의 다른 글

JAVA Threads  (2) 2011.03.24
Java Call by value, Call by reference  (2) 2011.03.24
The AWT Event Model  (0) 2011.03.24
Building GUIs & Java Graphics  (0) 2011.03.24
Java Core Packages  (2) 2011.03.24
1. 이벤트 핸들러
 1) 이벤트 소스 ex)버튼 
 2) 이벤트 ex)ActionEvent
 3) 이벤트 리스너 ex) addActionListener()
 4) 이벤트 핸들러  ex) actionPerformed(ActionEvent e)

2. ex) 혼자서 생성과 리스너 모두 실행하는 경우

 import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Button;
import java.awt.event.*;  //1. 패키지 임포트하자.
//2. 리스너 implements 하자.
public class EventModel3 implements WindowListener,ActionListener{
 private Frame f ;
 private Button btn ;
 private Font font;
 private void go(){
  f= new Frame("Event Model1");
  //4. 이벤트 소스에 이벤트 리스너등록하자.
  f.addWindowListener(this); //자신이 리스너가 된다.
  f.setLayout(new FlowLayout());
  font = new Font("Serif",Font.BOLD,30);
  btn = new Button("빨간색");
  btn.setFont(font);
  btn.addActionListener(this);
  btn.setBackground(Color.red);
  f.add(btn); 
  f.setSize(500, 400);
  f.setVisible(true);
 }
 //3. 이벤트 핸들러 메소드 오버라이드하자.
 public void windowClosing(WindowEvent e){ //종료 이벤트
  System.exit(0);
 } 
 public void actionPerformed(ActionEvent e){
  String str = e.getActionCommand();
  if (str.equals("빨간색")){
   f.setBackground(Color.red);
   btn.setLabel("파란색");
   btn.setBackground(Color.blue);
   btn.setForeground(Color.red);
   System.out.println( e.getActionCommand());
  }else{
   f.setBackground(Color.blue);
   btn.setLabel("빨간색");
   btn.setBackground(Color.red);
   btn.setForeground(Color.blue);
   System.out.println( e.getActionCommand());
  }   
 }  
 public void windowClosed (WindowEvent e){}
 public void windowOpened(WindowEvent e){}
 public void windowActivated(WindowEvent e){}
 public void windowDeactivated(WindowEvent e){}
 public void windowIconified(WindowEvent e){}
 public void windowDeiconified(WindowEvent e){} 
 public static void main(String[] args) {
  new EventModel3().go();
 }
}

 

2. 이벤트 종류. (자바는 이벤트 종류가 많지않다.)

 Action

 ActionListener

 actionPerformed(ActionEvent ActionEvent)

 Item

 ItemListener

 itemStateChanged(ItemEvent ItemEvent)

 Mouse

 MouseListener

 mousePressed(MouseEvent MouseEvent)
mouseReleased(MouseEvent MouseEvent)
mouseEntered(MouseEvent MouseEvent)
mouseExited(MouseEvent MouseEvent)
mouseClicked(MouseEvent MouseEvent)

 MouseMotion

 MouseMotionLi
stener

 mouseDragged(MouseEvent MouseEvent)
 mouseMoved(MouseEvent MouseEvent)

 Key

 KeyListener

 keyPressed(KeyEvent KeyEvent)

 keyReleased(KeyEvent KeyEvent)

 keyTyped(KeyEvent KeyEvent)

 Focus

 FocusListener

 focusGained(FocusEvent FocusEvent)

 focusLost(FocusEvent FocusEvent)

 Adjustment

 AdjustmentListener

 adjustmentValueChanged(Adjustment AdjustmentEvent Event)

 Component

 ComponnetListener

 componentMoved(ComponentEvent ComponentEvent)

 componentHidden(ComponentEventcomponentHidden(ComponentEvent)

 componentResized(ComponentEventcomponentResized(ComponentEvent)

 componentShown(ComponentEvent ComponentEvent)

 Window

 WindowListener

 windowClosing(WindowEvent WindowEvent) 

 windowOpened(WindowEvent WindowEvent)

 windowIconified(WindowEvent WindowEvent)

 windowDeiconfied(WindowEvent WindowEvent)

 windowClosed(WindowEvent WindowEvent)

 windowActivated(WindowEvent WindowEvent)

 windowDeactivated(WindowEvent WindowEvent)

 Container

 ContainerListener

 componentAdded(ContainerEvent ContainerEvent)

 componentRemoved(ContainerEvent ContainerEvent)

 Text

 TextListener

 textValueChanged(TextEvent TextEvent)

 


3. Adapter

 1) 이벤트 Listener들을 이미 상속받은 클래스로 필요한 메소드만 재정의 하여 쓸 수 있게된다. (코드 간소화)


'Programming > JAVA' 카테고리의 다른 글

Java Call by value, Call by reference  (2) 2011.03.24
The AWT Component Library  (1) 2011.03.24
Building GUIs & Java Graphics  (0) 2011.03.24
Java Core Packages  (2) 2011.03.24
Java Collections Framework  (2) 2011.03.24

+ Recent posts