Clean & Blue 자세히보기

전공/전공 마스터리

자바 프로그래밍 공부하면서 정리한 개념 및 구문, 메소드들 pt.2

_청렴 2022. 5. 17. 08:18
반응형

2022.01.13 - [전공/전공 마스터리] - 자바 프로그래밍 공부하면서 정리한 개념 및 구문, 메소드들

 

자바 프로그래밍 공부하면서 정리한 개념 및 구문, 메소드들

자바 프로그래밍 기초 - 자바 환경변수 설정 내PC(속성) -> 고급 시스템 설정 -> 고급 -> 환경변수 JAVA_HOME : 자바 설치 경로 PATH : 자바 설치 경로/bin - 온라인 자바 API 참조 링크 http://docs.oracle.com./..

aapslie94.tistory.com

 

자바의 이벤트 처리


- 이벤트 객체 종류와 이벤트 소스 종류

이벤트 객체 이벤트 소스
ActionEvent JButton, JList, JMenuItem, JTextField
ItemEvent : JCheckBox, JCheckBoxMenuItem, JList
KeyEvent : Component
MouseEvent : Component
FocusEvent : Component
TextEvent : TextField, TextArea
WindowEvent Window
AdjustmentEvent JScrollBar
ComponentEvent Component
ContainerEvent Container

 

- 이벤트 리스너 인터페이스와 추상메소드

이벤트 종류 리스너 인터페이스 리스너의 추상 메소드
Action ActionListener actionPerformed(ActionEvent)
Item ItemListener itemStateChanged(ItemEvent)
Key KeyListener keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)
Mouse MouseListener mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseClicked(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
Mouse MouseMotionListener mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
Focus focusListener focusGained(FocusEvent)
focusLost(FocusEvent)
Text TextListener textValueChanged(TextEvent)
Window WindowListener windowOpened(WindowEvent)
windowClosing(WindowEvent)
windowClosed(WindowEvent)
windowIconfied(WindowEvent)
windowDeiconfied(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
Adjustment AdjustmentListener adjustmentValueChanged(AdjustmentEvent)
Component ComponentListener componentHidden(ComponentEvent)
componentShown(ComponentEvent)
componentResized(ComponentEvent)
componentMoved(ComponentEvent)
Container ContainerListener componentAdded(ContainerEvent)
componentRemoved(ContainerEvent)

 -> 리스너 인터페이스는 인터페이스이기 때문에 추상 메소드들을 하나도 빠짐없이 오버라이딩하여 정의해야 한다.

 

- JButton b = (JButton)e.getSource(); 

 -> 이벤트 소스를 알아내는 메소드

 

- btn.addActionListener(new MyListener()) : 액션 리스너를 컴포넌트에 붙이는 메소드

 

- 이벤트 리스너들은 add로 시작하여 붙이는데 그 이유는, 동일한 이벤트에 대해 여러개의 서로 다른 이벤트 리스너를 중복하여 가질 수 있기 때문이다.

 

- 익명 클랙스 정의하는 방법

Jb[3].addMouseListener(new MouseAdapter() {
	public void mousePressed(MouseEvent e)
	{
		try {
			parameter = parameter.substring(0, parameter.length()-1); // 시작위치부터 마지막에서 하나를 뺀 위치까지의 문자열을 잘라낸다.
			textfield.setText(parameter);
		} catch(StringIndexOutOfBoundsException e1) {
			textfield.setText(parameter);
		}
		textfield.requestFocus();
	}
});

 -> 리스너 대신에 어댑터를 적어넣었지만 기능적으로도 정의하는 방법적으로도 똑같기 때문에 무방함

 

- 리스너 인터페이스에 대응하는 어댑터 클래스

 -> KeyAdapter, MouseAdapter, MouseMotionAdapter, FocusAdapter, WindowAdapter, ComponentAdapter, ContainerAdapter

 -> 나머지 인터페이스는 어차피 메소드가 하나밖에 없기 때문에 어댑터는 존재하지 않음

 

- KeyEvent 객체의 가상 키 종류

 -> VK_0 ~ VK_9, VK_A ~ VK_Z, VK_F1, ~ VK_F24, VK_HOME, VK_END, VK_PGUP, VK_PGDN, VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN, VK_CONTROL, VK_SHIFT, VK_ALT, VK_TAB, VK_UNDEFINED

 

 

기본적인 스윙 컴포넌트와 활용


- 스윙 컴포넌트의 공통 메소드

-> 컴포넌트의 모양과 관련된 메소드

void setForeground(Color) : 전경색 설정

void setBackground(Color) : 배경색 설정

void setOpaque(boolean) : 불투명성 설정

void setFont(Font) : 폰트 설정

Font getFont() : 폰트 리턴

 

-> 컴포넌트의 상태와 관련된 메소드

void setEnabled(boolean) : 컴포넌트 활성화/비활성화

void setVisible(boolean) : 컴포넌트 보이기/숨기기

boolean isVisible() : 컴포넌트의 보이는 상태 리턴

 

-> 컴포넌의 위치와 크기에 관련된 메소드

int getWidth() : 폭 리턴

int getHeight() : 높이 리턴

int getX() : x 좌표 리턴

int getY() : y 좌표 리턴

Point getLocationOnScreen() : 스크린 좌표상에서의 컴포넌트 좌표

void setLocation(int, int) : 위치 지정

void setSize(int, int) : 크기 지정

 

-> 컨테이너를 위한 메소드

Component add(Component) : 자식 컴포넌트 추가

void remove(Component) : 자식 컴포넌트 제거

void removeAll() : 모든 자식 컴포넌트 제거

Component[] getComponents() : 자식 컴포넌트 리스트 리턴

container getParent() : 부모 컨테이너 리턴

Container getTopLevelAncestor() : 최상위 부모 컨테이너 리턴

 

- JLabel, 레이블 컴포넌트

JLabel textLabel = new JLabel("사랑합니다."); // 문자열 레이블 생성
// or
ImageIcon image = new ImageIcon("images/sunset.jpg"); // 이미지 아이콘 생성
JLabel imageLabel = new JLabel(image); // 이미지 레이블 생성
// or
JLabel label = new JLabel("사랑합니다.", image, SwingConstants.CENTER); // 가운데 정렬

-> JLabel에 담을 수 있는 이미지 형식은 png, gif, jpg 밖에 없음

 

- JButton, 버튼 컴포넌트

ImageIcon normalIcon = new ImageIcon("images/normalIcon.gif");
ImageIcon rolloverIcon = new ImageIcon("images/rolloverIcon.gif");
ImageIcon pressedIcon = new ImageIcon("images/pressedIcon.gif");

JButton button = new JButton("테스트버튼", normalIcon);
button.setRolloverIcon(rolloverIcon); // 마우스가 올라갔을때 이미지
button.setPressedIcon(pressedIcon); // 마우스로 눌렀을때 이미지 세팅

- 버튼과 레이블 컴포넌트의 정렬

-> 수평 정렬

void setHorizontalAlignment(int align)

align : SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.RIGHT

 

-> 수직 정렬

void setVerticalAlignment(int align)

align : SwingConstants.TOP, SwingConstants.CENTER, SwingConstants.BOTTOM

 

- JCheckBox

ImageIcon cherryIcon = new ImageIcon("images/cherry.jpg");
ImageIcon selectedCherryIcno = new ImageIcno("images/selectedCherry.jpg");

JCheckBox cherry = new JCheckBox("체리", cherryIcon);
cherry.setSelectedIcon(selectedCherryIcon); // 선택 상태를 표시하는 이미지 등록
// or
JCheckBox pear = new JCheckBox("배", true); // 선택된 상태로 생성

cherry.setSelected(true); // 선택상태로 변경

 

- Item 이벤트 : 체크박스, 라디오버튼과 사용됨

-> ItemListener 인터페이스

void itemStateChanged(ItemEvent e) 

int getStateChange() : 체크박스 상태 변화 리턴

Object getItem() : 이벤트를 발생시킨 아이템 리턴


- JRadioButton, 라디오버튼 컴포넌트

ButtonGroup group = new ButtonGroup();

JRadioButton apple = new JRadioButton("사과");
JRadioButton pear = new JRadioButton("배");
JRadioButton cherry = new JRadioButton("체리");

group.add(apple);
group.add(pear);
group.add(cherry);

container.add(apple);
container.add(pear);
container.add(cherry);

 

- JTextField

JTextField tf = new JTextField("hi", 20); // 20개 문자크기의 텍스트필드 생성
tf.setEditable(false); // 편집 불가
tf.setText("hello");
tf.setFont(new Font("고딕체", Font.ITALIC, 20)); // 폰트 설정

 

- JTextArea

container.add(new JScrollPane(new JTextArea("hello", 7, 20)));
// 7줄, 20문자 짜리 크기의 스크롤이 되는 텍스트영역 생성

 

- JList

String [] fruits = {"apple", "banana", "kiwi", "mango", "pear", "peach"};

JList strList = new JList(fruits); // 배열을 인자값으로 넣는다.

JScrollPane pane = new JScrollPane(strList); // 스크롤 가능한 리스트 만들기

 

- JComboBox

String [] fruits = {"apple", "banana", "kiwi", "mango", "pear"};

JComboBox = strCombo = new JComboBox(fruits);

-> addItem(), removeItem(), removeItemAt(), removeAllItem() 등의 메소드가 있다.

-> 액션이벤트와 아이템이벤트를 이용할 수 있음

 

- JSlider

-> 생성자

JSlider()

JSlider(int orientation) : JSlider.HORIZONTAL, JSlider.VERTICAL의 인자값중 하나

JSlider(int min, int max, intval)

JSlider(int orientation, int min, int max, int val)

-> 메소드

setValue(), setOrientation(), setMaximun(), setMinimum(), 

void setPointLabels(boolean b) : 라벨을 보이게 하는 메소드

void setPointTicks(boolean b) : 눈금을 보이게 하는 메소드

void setPointTrack(boolean b) : track을 보이게 하는 메소드

void setMinorTickSpacing(int space) 

void setMajorTickSpacing(int space)

 

-> JSlider는 Change 이벤트를 사용함

 

 

그래픽


- 컴포넌트의 모양은 컴포넌트가 스스로 그림

-> void painfComponent(Graphics g) 메소드를 통해서 스스로를 그림

-> 해당 메소드를 오버라이딩해서 사용자가 원하는 모양으로 그릴 수 있음

-> Graphics g를 그래픽 컨텍스트라고 부름

 

class MyPanel extends JPanel {
	public void paintComponent(Graphics g) {
    	super.paintComponent(g);
        g.setColor(Color.BLUE);
        g.drawRect(10, 10, 50, 50);
        }
     }
}

-> 예시

 

- void setColor(Color color) : 색상 선택하기

- void setFont(Font font) : 폰트 설정하기

 

- 문자열 그리기

void drawString(String str, int x, int y)

 

- 도형 그리기

void drawLine(int x1, int y1, int x2, int y2) : 선 그리기

void drawOval(int x, int y, int w, int h) : w*h에 내접하는 타원 그리기

void drawRect(int x, int y, int w, int h)

void drawRoundRect(int x, int y, int w, int h, int arcWidth, int arcHeight) : 모서리는 수평 반지름(arcWidth)와 수직 반지름(arcHeight)를 이용하여 그림

 

- 원호와 폐다각형 그리기

void drawArc(int x, int y, int w, int h, int startAngle, int arcAngle) : 3시 방향이 0도의 기점, startAngle에서 arcAngle까지의각도만큼 원호를 그림

void Polygon(int []x, int []y, int n) : x, y 배열에 저장된 점들 중 n개를 연결하는 폐다각형을 그림

 

- 도형 칠하기

fillRect(), fillArc(), fillOval(), fillPolygon() 등

 

- 이미지 그리기

boolean drawImage(Image img, int x, int y, Color bgColor, ImageObserver observer) : 원본 크기로 그리기

 -> Color bgColor는 백그라운드 색상으로 빼도 되는 옵션, observer는 보통 this를 사용함

boolean drawImage(Image img, int x, int y, int w, int h, Color bgcolor, ImageObserver observer) : 크기 조절하여 그리기

boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgColor, ImageObserver observer) : 원본의 일부분을 크기 조절하여 그리기,

 -> img의 (sx1, sy1)에서 (sx2, sy2)까지의 부분을 (dx1, dy1),(dx2, dy2)에 그림


- 이미지 객체 만들기

ImageIcon icon = new ImageIcon("images/image0.jpg");
Image img = icon.getImage(); // 순수이미지 추출하기

 

- 클리핑

void setClip(int x, int y, int w, int h) : 클립 영역 지정

void clipRect(int x, int y, int w, int h) : 기존 클리핑 영역과 현재 (x,y)에서 w*h 크기로 지정된 영역의 교집합을 새로운 클리핑 영역으로 지정

 

- repaint() : 다시 그리기

 

 

고급 스윙 컴포넌트


- 메뉴 만들기

void createMenu() {
	JMenuBar mb = new JMenubar();
    JMenu fileMenu = new JMenu("File");
    
    // File 메뉴에 메뉴아이템 삽입
    fileMenu.add(new JMenuItem("New");
    fileMenu.add(new JMenuItem("Open");
    fileMenu.addSeparator(); // 분리선 삽입
    fileMenu.add(new JMenuItem("Save");
    fileMenu.add(new JMenuItem("Save As");
    
    // 메뉴바에 메뉴 삽입
    mb.add(fileMenu);
    mb.add(new JMenu("Edit"));
    mb.add(new JMenu("Source"));
    mb.add(new JMenu("Project"));
    mb.add(new JMenu("Run"));
    
    setJMenuBar(mb); // 메뉴바를 프레임에 삽입
}

-> 액션이벤트를 이용해 이벤트를 만듦

-> e.getActionCommand() 메소드를 이용해 선택된 메뉴아이템의 문자열을 리턴 받음

 

- 툴바

void createToolBar() {
	JToolBar toolBar = new JToolBar("kitae Menu");
    // toolBar.setFloatable(false) 를 쓰면 툴바를 이동시킬수 없게 됨
    
    toolBar.add(new JButton("New"));
    toolBar.add(new JButton(new ImageIcon("images/open.jpg")));
    toolBar.addSeparator(); // 구분선 삽입
    toolBar.add(new JButton(new ImageIcon("images/save.jpg")));
    toolBar.add(new JLabel("search"));
    toolBar.add(new JTextField("text field"));
    JComboBox combo = new JComboBox();
    combo.add("Java");
    combo.add("C#");
    combo.add("C");
    combo.add("C++");
    tooBar.add(combo);
    
    // 툴바를 contentPane에 부착한다.
    contentPane.add(toolBar, BorderLayout.NORTH);
}

-> 컨텐트팬은 디폴트 배치관리자가 BorderLayout이다.

 

 

- 툴팁

void setToolTipText(String str)

-> 모든 컴포넌트들이 툴팁을 가질 수 있음

 

- 툴팁매니저와 툴팁 시간 제어

// 툴팁매니저 객체 얻기
ToolTipManager m = ToolTipManager.sharedInstance(); 
// 툴팁 활성화
m.setEnabled(true);
// 마우스가 올라온 후 툴팁이 출력되기까지 시간 설정
m.setInitialDelay(1000);
// 툴팁이 켜져 있는동안의 지속시간 설정
m.setDismissDelay(1000);

 

- 다이얼로그 만들기

-> 메소드

JDialog()

JDialog(Frame owner)

JDialog(Frame owner, String title)

JDialog(Frame owner, String title, boolean modal)

class MyDialog extends JDialog {
	public MyDialog(JFrame frame, String title) {
    	super(frame, title); // frame은 다이얼로그 주인이며 title은 다이얼로그의 타이틀
    }
}

-> 새로 정의 할 경우 

 

public class DialogEx extends JFrame {
	MyDialog dialog;
    
    public DialogEx() {
    
    	dialog = new Mydialog(this, "Test Dialog");
    }
}

-> owner frame에서는 생성자를 불러올때 this를 이용해 부른다.

 

- 모달 다이얼로그와 모달리스 다이얼로그

모달 다이얼로그는 다이얼로그가 풀력되면 일단 해당 다이얼로그를 닫기 전까진 다른 작업을 전혀 할 수 없음

JDialog(Frame owner, String title, boolean modal)

-> 세번째 인자를 true로 주면 됨

 

- 팝업 다이얼로그

JOptionPane 클래스는 팝업 다이얼로그를 생성할 수 있는 static 메소드를 여러개 지원함

팝업다이얼로그는 모두 모달 타입임.

 

입력 다이얼로그

static String JOptionPane.showInputDialog(String msg)

-> msg : 다이얼로그 메세지

-> 리턴 : 사용자가 입력한 문자열

 

확인 다이얼로그

static int JOptionPane.showConfirmDialog(Component parentComponent, Object msg, String title, int optionType)

-> parentcomponent : 다이얼로그가 출력되는 영역의 범위 지정을 위해 사용하는 부모 컴포넌트, null 이면 전체 화면 중앙에 출력

-> msg : 다이얼로그 메세지

-> title : 다이얼로그 타이틀

-> optionType : YES_NO_OPTION, YES_NO_CANCEL_OPTION, OK_CANCEL_OPTION

-> 리턴 : YES_OPTION, NO_OPTION, CANCEL_OPTION, OK_OPTION, CLOSED_OPTION

 

메세지 다이얼로그

static void JOptionPane.showMessageDialog(Component parentComponent, Object msg, String title, int messageType)

-> messageType : ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, PLAIN_MESSAGE

 

- 파일 다이얼로그

import javax.swing.filechooser.*; // 파일 필터를 사용하기 위한 패키지

JFileChooser chooser = new JFileChooser(); 

FileNameExtensionFilter filter = new FileNameExtenionFilter("JPG & GIF Images", "jpg", "gif");
// 첫번째 인자는 파일 종류 창에 출력될 메세지
// 두번째 인자부터 필터링할 파일들

chooser.setFileFilter(filter); // 파일 필터 설정
chooser.addChoosableFileFilter(filter); // 추가적인 파일 필터 설정

int ret = chooser.showOpenDialog(null); // 파일 열기 다이얼로그 출력
// null 은 범위 지정을 할 parentComponent를 의미 
// 리턴값으로 APPROVE_OPTION CANCEL_OPTION, ERROR_OPTION

if(ret == JFileChooser.APPROVE_OPTION) {
	String pathName = chooser.getSelectedFile().getPath(); // 선택한 파일 경로
    String fileName = chooser.getSelectedFile().getName(); // 선택한 파일 이름
}

int ret = chooser.showSaveDialog(null); // 파일 저장 다이얼로그

 

- 컬러 다이얼로그

JColorChooser chooser = new JColorChooser(); 

-> 컬러 chooser 객체 생성

Color selectedColor = chooser.showDialog(null, "Color", Color.YELLOW);

-> 다이얼로그 생성, 타이틀은 Color, 초기색상은 노란색

if(selectedColor != null) 을 이용한 판별이 필요

 

- 탭팬

JTabbedPane createTabbedPane() {
	 JTabbedPane pane = new JTabbedPane();
     pane.add("tab1", new JLabel());
     pane.add("tab2", new JLable());
     pane.add("tab3", new MyPanel());
     return pane;
 }

 

 

스레드와 멀티태스킹


- 자바에는 프로세스 개념이 존재하지 않고 스레드 개념만 존재, 자바 가상 기계(JVM)은 멀티스레딩만 지원함

-> 자바 스레드란 JVM에 의해 스케줄되는 실행 단위 코드 블록

 

- 스레드가 생성되면 스레드에 관련된 정보(TCB, Thread Control Block)가 생성되며 JVM에 의해 관리됨

 

- Thread 클래스의 메소드 정리

Thread의 메소드 내용
Thread()
Thread(Runnable target)
Thread(String name)
Thread(Runnable target, String name)
단순한 스레드 객체 생성
Runnable 객체인 target을 이용하여 스레드 객체 생성
이름이 name인 스레드 객체 생성
Runnable 객체를 이용하여, 이름이 name인 스레드 객체 생성
void run() 스레드 코드로서 JVM에 의해 호출됨, 개발자는 반드시 오버라이딩하여 스레드 코드를 작성하여야 함. 이 메소드가 종료되면 스레드도 종료
void start() JVM에게 스레드 실행을 시작하도록 요청
void interrupt() 스레드 강제 종료, run()에 try-catch 인터럽트 예외 처리가 되어있지 않으면 해당 메소드를 써도 종료되지 않음
static void yield() 다른 스레드에게 실행을 양보함. 이때 스레드 스케줄링이 시행되며 다른 스레드를 선택하여 실행시킴
void join()  스레드가 종료할 때 까지 기다린다.
long getId() 스레드의 ID값 리턴
String getName() 스레드의 이름 리턴
int getPriority() 스레드의 우선순위 값 리턴
void setPriority(int n) 스레드의 우선순위 값을 n으로 변경
Thread.State getState() 스레드의 상태 값 리턴
static void sleep(long mills) 스레드는 mills 시간 동안 잔다. mills는 밀리초 이며 try-catch문과 함깨 써야함
static Thread currentThread() 현재 실행 중인 스레드 객체의 레퍼런스 리턴

 

- Thread 클래스 작성 및 사용법

class TimerThread extends Thread {
	int n = 0;
    public void run() {
    	while(true) { // 무한 루프 실행
        System.out.println(n);
        n++;
        try { //sleep() 함수를 쓰기 위해 꼭 써야 함
        	sleep(1000); // 1초 동안 잠을 잠
        }
        catch(InterruptedException e) {
        	return; 
        ]
    }
}

public class TestThread {
	public static void main(String [] args) {
    	TimerThread th = new TimerThread();
        th.start(); // 비로소 생성된 객체를 스케줄링이 
        //가능하도록 JVM에 지시함
    }
}

 

- Runnable 인터페이스 

 -> 추상 메소드 run() 하나만 가지고 있음

class TimerRunnable implements Runnable {
	int n = 0;
    public void run() {
    	while(true) { // 무한 루프 실행
        System.out.println(n);
        n++;
        try { //sleep() 함수를 쓰기 위해 꼭 써야 함
        	sleep(1000); // 1초 동안 잠을 잠
        }
        catch(InterruptedException e) {
        	return; 
        ]
    }
}

public class TestThread {
	public static void main(String [] args) {
    	TimerThread th = new TimerThread(new TimerRunnable()); //Runnable 생성자를 
        //스레드 객체 생성 시 인자로 넣어줌
        th.start(); 
    }
}

 

- 스레드 관리 정보(TCB)

 -> 이름, ID, PC, 상태, 우선순위, 그룹, 레지스터 스택

 

- 데몬 스레드 : JVM이 스스로 필요에 의해 사용되는 스레드 -> 가비지 컬렉션 스레드

- 일반 스레드 : 응용프로그램에서 생성한 스레드 -> main()

 

- 스레드 생명주기(상태)

NEW 스레드 생성
RUNNABLE 스레드 실행 혹은 실행 준비
WAITING 스레드가 어떤 객체 a에 대해 a.wait()을 호출하고 무한정 대기, 다른 스레드가 a.notify(), a.notifyAll()을 불러주기를 기다리는 상태
TIMED_WAITING 스레드가 sleep(int n)을 호출하여 잠자는 중
BLOCK 스레드가 I/O작업을 요청하여 작업이 완료되기를 기다리는 상태
TERMINATED 스레드 종료

 

- 스레드 동기화란 공유 데이터에 접근하고자 하는 다수의 스레드가 서로 순서대로 충돌 없이 공유 데이터를 배타적으로 접근하기 위해 상호 협력하는 것

 

- 임계 영역 : 공유 데이터를 다루는 프로그램 코드

 

- 자바의 스레드 동기화를 위한 Synchronized 키워드

-> synchronized 블록은 진입할 때 락을 걸고, 빠져 나올때 락을 푸는 동작이 자동으로 이루어짐

 -> 메소드 전체를 임계 영역으로 지정

synchronized void add() { // 메소드 앞에 키워드를 적는다.
	int n = getCurrentSum();
    n+=10;
    setCurrentsum(n);
}

-> 임의의 코드 블록을 임계 영역으로 지정

void() execute() {
	..........
    synchronized(this) // 중간에 키워드를 적고 자기자신을 가리키도록 함
    	int n = getCurrentSum();
        n+=10;
        setCurrentSum(n);
    }
    ..........
}

 

- 동기화 객체(공유될 자원)의 메소드

wait() : 다른 스레드가 이 객체의 notify()를 불러줄 때까지 대기

notify() : 이 객체에 대기중인 스레드를 깨워 RUNNABLE 상태로 만듦

notifyAll() : 이 객체에 대기중인 모든 스레드를 깨우고 모두 RUNNABLE 상태로 만듦

 -> notifyAll() 메소드는 사용시 데이터 충돌이 일어 날수 있음, 깨어난 스레드 중 한 개만 데이터를 소유하고 나머지는 다시 wait()을 호출하도록 해야 함