bactoria 2018. 1. 17. 21:20

Thread 만드는법은 2가지

1. Thread 클래스 상속

2. Runnable 인터페이스 구현


지금 소켓통신에 쓸 방법이 2번이라서 2번을 살펴본다. 

t.start();


    public class ServerThread implements Runnable {
        Server s;
        Socket socket;
        public ServerThread(Server s){
            this.Server = s;
        }

        public synchronized void run(){
            try{
                   socket = s.getSocket();
                }
            }catch(Exception e){
              System.out.println("비정상 종료");
            }
        }
        public Socket getSocket(){    // Thread에 Server의 socket 전달 위함.
           return socket;
        }
        


ServerThread 클래스는 Thread가 아니다.

따라서 ServerThread 객체를 만들고, Thread를 생성해야하는데,

Thread 생성할 때 ServerThread객체를 매개변수에 넣어서 Thread를 만들어야한다.

아래처럼


public class Server {  
        public static void main(String[] args) {
            ServerThread st1 = new ServerThread(this); // this 는 Server객체이다.
     
            Thread t1 = new Thread(st1);

            t1.start(); // start(); 하면 st1.run 을 하게 되있다.  
        }   

    }