| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
- JavaScript
- Programming
- 비지니스영어
- Python
- Mac
- db
- 영어
- 오라클 디비
- 머신러닝
- 자바
- sap mm
- 유럽여행
- 딥러닝
- SAP ERP
- 자바스크립트
- 오라클
- 노드
- nodejs
- Oracle DB
- 파이썬
- SAP
- IT
- node.js
- Spring Framework
- SAP ABAP
- oracle
- docker
- ABAP
- 도커
- Java
- Today
- Total
JIHYUN JEONG
[java] 엄마도 이해하는 자바 기본 5일차 본문
□ 복습을 위한 예제 (Class 생성연습)
- mplyee 직원 클래스 (super클래스)
ㅁ 필드
- String num;
- String name;
- int salary
ㅁ 매서드
public _______ getBonus () {
return salary * 1.1
ㅁ 생성자 생성
- num, name, salary를 입력하는
manager 클래스 (sub 클래스)
- String dept;
- public Manager(0,0,0,0) { // 즉 dept까지 포함해서 생성자
}
getBonus() overring
salary * 1.3
main()
[소스코드]
package asianaidt.test_218;
public class Employee {
String num;
String name;
int salary;
public Employee(String num, String name, int salary){
this.num = num;
this.name = name;
this.salary = salary;
}
public double getBonus(){
return salary * 1.1;
}
}
package asianaidt.test_218;
public class Manager extends Employee{
public String dept;
public Manager(String num, String name, int salary, String dept){
super(num,name,salary);
this.dept = dept;
}
public double getBonus(){
return salary * 1.5;
}
public void printBonus(Employee x){
System.out.println(x.getBonus());
}
public static void main(String[] args) {
Employee e = new Employee("000","None",1000);
Manager m = new Manager("111","Jone",1000,"재무");
m.printBonus(e);
m.printBonus(m); // type과 상관없이 overriding 되면
// System.out.println(e.name);
}
}
[예제]
TableDemo.java
VectorTable.java
package asianaidt.swing;
/* Example of JTable using Vector */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
public class VectorTable extends JFrame{
Vector outer, in, in2, in3, title;
JTable table;
public VectorTable() {
super("TableDemo");
title = new Vector();
title.add("num");
title.add("name");
title.add("address");
outer = new Vector();
in = new Vector(); // 실제 데이터를 in 에 넣음
in.add("111");
in.add("diane soyer");
in.add("seattle");
in2 = new Vector(); // 실제 데이터를 in 에 넣음
in2.add("222");
in2.add("diane soyer");
in2.add("kkkk");
outer.add(in); // in을 다시 outer에 넣음
outer.add(in2);
table= new JTable(outer,title);
JScrollPane scrollPane = new JScrollPane(table);
Container c = getContentPane();
c.add(new JLabel("TableDemo",JLabel.CENTER), "North");
c.add(scrollPane, "Center");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
VectorTable frame = new VectorTable();
frame.pack();
frame.setVisible(true);
}
}
□ IO
FileChooserTest.java
package asianaidt.io;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
public class FileChooserTest extends JPanel implements ActionListener {
static private final String newline = "\n";
JButton openButton, saveButton;
JTextArea log;
JFileChooser fc; //*** 노트패드에 생성해줄것
public FileChooserTest() {
super(new BorderLayout());
log = new JTextArea(5,20);
log.setEditable(false);
JScrollPane logScrollPane = new JScrollPane(log);
fc = new JFileChooser(); //*** 객체 생성
openButton = new JButton("Open a File...");
openButton.addActionListener(this);
saveButton = new JButton("Save a File...");
saveButton.addActionListener(this);
JPanel buttonPanel = new JPanel(); //use FlowLayout
buttonPanel.add(openButton);
buttonPanel.add(saveButton);
//Add the buttons and the log to this panel.
add(buttonPanel, BorderLayout.PAGE_START);
add(logScrollPane, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
//Handle open button action.
if (e.getSource() == openButton) {
//showOpenDialog(): 화면에 열기 창을 띄워 줌
int returnVal = fc.showOpenDialog(FileChooserTest.this); // 파일 선택기 창이 뜸, (FileChooseTest.this, 이 공간엔 메인 창을 넣어줌)
if (returnVal == JFileChooser.APPROVE_OPTION) { //열기버튼 클릭시
File file = fc.getSelectedFile();
//This is where a real application would open the file.
log.append("Opening: " + file.getName() + "." + newline); // newline = 줄 바꿈 변수
} else { //취소 버튼 클릭시
log.append("Open command cancelled by user." + newline);
}
//Handle save button action.
} else if (e.getSource() == saveButton) {
//showSaveDialog(): 화면에 저장 창을 띄워 줌
int returnVal = fc.showSaveDialog(FileChooserTest.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would save the file.
log.append("Saving: " + file.getName() + "." + newline);
} else {
log.append("Save command cancelled by user." + newline);
}
}
}
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true); // 모든 작업 전에 해줘야 함
JDialog.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("FileChooserTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JPanel newContentPane = new FileChooserTest();
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
}
}
□ Thread
- 프로세스 내의 개별적인 실행 흐름
- 프로세스는 프로그램 실행에 필요한 자원과 thread로 구성
- 모든 프로세스는 최소 하나 이상의 thread가 존재해야 실행가능
□ Thread - MultiThread
- 둘 이상의 thread를 이용한 프로그램
- CPU, 자원 이용률을 높임
- 사용자 응답성이 향상됨
□ Thread 구조
□ Thread 생성방식
1. Thread class 상속
2. Runnable interface 구현
→ 두 방법 모두 run() 구현해야 함 (★ 중요함)
; thread에 시킬 작업 내용 기술 하는 곳
□ Thread 생성방식 - 1. Thread class 상속
[예시]
□ Thread 생성방식 - 2. Runnable interface 구현
[예시]
□ Thread Synchronization
- 다수의 thread가 공유 데이터에 접근해서 작업할 경우 thread간의 간의 간섭 현상이 발생
- 이를 방지하기 위해 thread간에 동기화를 시켜줌 ; 일종의 lock
[예제]
int count =0;
Thread a, b, c;
public void run(){
add();
}
public void add(){
count++; // problem!!
System.out.println(count);
}
1. 연산전 count 읽기
2. 연산 0 -> 1
3. 연산후 count 쓰기
int count =0;
Thread a, b, c;
public void run(){
add();
}
public syvoid add(){
count++; // problem!!
System.out.println(count);
}
□ IO
□ Thread
package asianaidt.thread;
public class MainTest implements Runnable{
public void go(){
System.out.println("go method....");
}
public static void main(String[] args) {
MainTest m = new MainTest();
Thread t = new Thread(m);
t.start();
// m.go(); // 사용자 정의 매소드가 main 쓰레드 보다 빠르다
try {
t.join(); // main 매소드 부터 할 수 있게
m.go();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
System.out.println("run method..");
}
}
package asianaidt.thread;
public class Monitors implements Runnable {
Monitors() {
Thread ta = new Thread(this,"tom");
Thread tb = new Thread(this,"jeery");
ta.start();
tb.start();
}
public void run() {
kitchen();
bedroom();
}
public synchronized void kitchen() {
//currentThread(): 현재 실행 중인 스레드를 알아내는 함수
System.out.println(Thread.currentThread().getName() + " 부엌에 들어옴");
try{
Thread.sleep(1000);
}catch(Exception w){}
System.out.println(Thread.currentThread().getName() + " 부엌에서 나감");
}
public synchronized void bedroom() {
System.out.println(Thread.currentThread().getName() + " 침실에 들어옴");
try{
Thread.sleep(1000);
}catch(Exception w){}
System.out.println(Thread.currentThread().getName() + " 침실에서 나감");
}
public static void main(String args[]) {
Monitors m = new Monitors();
}
}
package asianaidt.thread;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ThreadClock extends JFrame implements ActionListener, Runnable{
JTextField tf,up;
JTextArea ta;
JLabel la;
boolean flag=true;
String msg;
public ThreadClock() {
super("Thread Clock");
setLayout(new BorderLayout());
JLabel la = new JLabel("hello chat",JLabel.CENTER); // 북쪽에다가 붙일꺼
// setDefaultCloseOperation(EXIT_ON_CLOSE); // 창 닫기 버튼을 누르면 강제 종료
Container c = getContentPane();
c.add(la, "North");
ta = new JTextArea(5,10);
tf = new JTextField(10);
JScrollPane pane1 = new JScrollPane(ta);
up = new JTextField(15);
up.setEditable(false);
c.add(up,"North");
c.add(pane1,"Center");
addWindowListener(new WindowAdapter(){
// WindowAapter가 WindowListener을 implement 함, WindowAdapter를 extends하고 이름은 없는 것을 하나 만듬
public void windowClosing(WindowEvent w){
flag = false;
System.out.println("프로그램 종료!!!");
setVisible(false);
System.exit(0);
}
}
);
ta.setEditable(false); // 작성을 못하게 함
//c.add(pane1, "Center");
tf = new JTextField(10);
c.add(tf, BorderLayout.SOUTH);
setSize(300, 200);
// pack();
setVisible(true);
tf.requestFocus();
Thread t = new Thread(this); // 자기가 가지고 있음
t.start();
tf.addActionListener(this);
}
public static void main(String args[]) {
new ThreadClock();
}
@Override
public void actionPerformed(ActionEvent e) {
String msg = tf.getText();
// ta.append("[Guest] : ");
ta.append("[Guest]>" + msg);
ta.append("\n");
tf.setText("");
}
@Override
public void run() {
// thread가 일할 부분, 시간 정보 알아내서 up에 붙이기
while(true){
Date d = new Date();
up.setText(d.toString());
// sextText Type = String -> d type을 String으로 바꿔줌
}
}
}
// Thread 생성방식 - 1. Thread class 상속 //
package asianaidt.thread;
class ThreadSample1 extends Thread{ // ThreadSample1은 Thread Type
public void run(){ // thread작업 내용이 있는 함수
System.out.println("thread is running...." + getName());
}
}
public class ThreadTest1 {
public static void main(String[] args) {
// 상속관계 때문에 Thread가 먼저 만들어진다, 그리고 sam1 = thread
ThreadSample1 sam1 = new ThreadSample1(); // thread 생성
ThreadSample1 sam2 = new ThreadSample1(); // thread 생성
ThreadSample1 sam3 = new ThreadSample1(); // thread 생성
sam1.start();
// 일하러 보냄, start() 하는 순서대로 작업을 안할 수도 있다.
sam2.start();
sam3.start();
}
}
// Thread 생성방식 - 2. Runnable interface 구현 //
package asianaidt.thread;
class ThreadSamle2 implements Runnable{
public void run(){
System.out.println("thread is running..."+getName());
// 에러 발생 쓰레드가 아니기 때문
System.out.println("thread is running..."+Thread.currentThread().getName());
// 에러 발생 쓰레드가 아니기 때문
}
}
public class ThreaTest2 {
public static void main(String[] args) {
ThreadSamle2 sam1 = new ThreadSamle2();
// 방법 1 [쓰레드는 3개, run() 작업내용1개]
Thread t = new Thread(sam1);
// sam1은 Thread가 일할 Method를 가지고 있음
Thread t1 = new Thread(sam1);
Thread t2 = new Thread(sam1);
t.start();
t1.start();
t2.start();
// 방법 2 [ 쓰레드 3개, run() 작업내용 3개 ]
ThreadSamle2 sam2 = new ThreadSamle2();
ThreadSamle2 sam3 = new ThreadSamle2();
ThreadSamle2 sam4 = new ThreadSamle2();
Thread t3 = new Thread(sam2);
Thread t4 = new Thread(sam3);
Thread t5 = new Thread(sam4);
t3.start();
t4.start();
t5.start();
}
}
'Information Technology > Java' 카테고리의 다른 글
| [java] 엄마도 이해하는 자바 기본 6일차 (2) (0) | 2013.02.19 |
|---|---|
| [java] 엄마도 이해하는 자바 기본 6일차 (1) (0) | 2013.02.19 |
| [java] 엄마도 이해하는 자바 기본 4일차 (0) | 2013.02.18 |
| [java] 엄마도 이해하는 자바 기본 3일차 (0) | 2013.02.18 |
| [java] 엄마도 이해하는 자바 기본 2일차 (0) | 2013.02.18 |
TableDemo.java