728x90
SMALL
#스레드 사용 방법
Thread
-상속
Runnable
-람다
-구현체는 thread생성자에 넘기는 방법
- 스레드클래스
package java;
import java.awt.Toolkit;
public class BeepThread extends Thread {
@Override
public void run() {
Toolkit tk = Toolkit.getDefaultToolkit();
while(true) {
tk.beep();
try {
System.out.printf("[%s] thread is running\n ", Thread.currentThread().getName());
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
- Application
package java;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
// TODO Auto-generated method stub
final BeepThread thread = new BeepThread();
thread.start();
Scanner in = new Scanner(System.in);
while(true) {
int valueFromKeyboard = in.nextInt();
System.out.println("main " + valueFromKeyboard);
}
}
}
#기존실행흐름
main ----->블로킹
#스레드 실행흐름
main ----->블로킹
thread --------------->
#웹서버 스레드(씽글)
main -----> 접속대기 --->접속(socket) --->응답해줌 --->접속대기
- runnable
import java.io.*;
import java.net.Socket;
public class RequestHandler implements Runnable {
private Socket client;
public RequestHandler(Socket client) {
this.client = client;
}
@Override
public void run() {
System.out.println("사용자가 들어왔음.");
try (
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
) {
final BufferedReader br = new BufferedReader(new InputStreamReader(in));
final DataOutputStream dos = new DataOutputStream(out);
String readLine;
while (!(readLine = br.readLine()).equals("")) {
System.out.println(readLine);
}
System.out.println("v");
final byte[] bytes = "message".getBytes();
response200Header(dos, bytes.length);
responseBody(dos, bytes);
Thread.sleep(10000);
System.out.println(Thread.currentThread().getName() + " 뭔가 다하고 끝냄");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private void response200Header(DataOutputStream dos, int lengthOfBodyContent) {
try {
dos.writeBytes("HTTP/1.1 200 OK \r\n");
dos.writeBytes("Content-Type: text/html;charset=utf-8\r\n");
dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n");
dos.writeBytes("\r\n");
} catch (IOException e) {
}
}
private void responseBody(DataOutputStream dos, byte[] body) {
try {
dos.write(body, 0, body.length);
dos.flush();
} catch (IOException e) {
}
}
}
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Application {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(1905)) {
Socket client;
System.out.println("while 바깥");
while ((client = serverSocket.accept()) != null) {
System.out.println("사용자 옴");
final RequestHandler handler = new RequestHandler(client); // runnable
final Thread thread = new Thread(handler);
thread.start();
System.out.println("스레드에게 위임");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
#InputStream
-int read(byte[] buf)
파마리터 : 읽을 값을 저장하는 공간
반환값 : 읽은 바이트 수
void close() : 자원 반납 및 입력 스트림 종류(필수)
#OutputStream(프로그램이출발지)
-void write(byte[byte[] buf])
파라미터 : 출력 스트림으로 buf를 보냄
-void flush();
-void close() : 자원 반납 및 츨력스트림 종류(필수)
2.문자기반 스트림
Reader(입력, 도착지)
-int read(char[] cbuf)
파라미터 : cbuf에 문자열을 담음
반환: 읽은 문자개수
Writer(출력, 출발지)
-void write(char[] cbuf)
파라미터 : cbuf에 있는 내용을 출력으로 보냄
void write(String str)
파라미터 : 출력으로 보낼 문자열
flush()
close()
- RequestHandlingTask
import java.io.*;
import java.net.Socket;
public class RequestHandlingTask implements Runnable {
private final Socket socket;
public RequestHandlingTask(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try (
final InputStream in = socket.getInputStream(); // from client
final OutputStream out = socket.getOutputStream(); // to client
) {
// input
final BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine;
while (!(readLine = br.readLine()).equals("")) {
System.out.println(readLine);
}
// output
final String body = "한국말도 돼요?";
final byte[] raw = body.getBytes();
final DataOutputStream dos = new DataOutputStream(out);
// 헤더 쓰는 부분
dos.writeBytes("HTTP/1.1 200 OK \r\n");
dos.writeBytes("Content-Type: text/html;charset=utf-8\r\n");
dos.writeBytes("Content-Length: " + raw.length + "\r\n");
dos.writeBytes("\r\n");
// 바디 쓰는 부분
dos.write(raw, 0, raw.length);
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
728x90
LIST
'JAVA > Java' 카테고리의 다른 글
201106_32 상속 (0) | 2020.11.06 |
---|---|
20201105_29 jdbc문제 및 해결 (0) | 2020.11.05 |
20201104_28 jdbc (0) | 2020.11.04 |
20201104_27 Review (0) | 2020.11.04 |
20201103_27 A와 B 돈인출, review (0) | 2020.11.03 |
댓글