package threadFight;

public class main
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Unit unit1 = new Unit();
Thread th = new Thread(unit1);
th.start();
}
}

class Unit implements Runnable
{
public String name = "홍길동";
public int hp = 50;
@Override
public void run()
{
while(this.isLive())
{
// TODO Auto-generated method stub
//랜덤으로 상대에게 타격한다.
int at = (int)(Math.random()*6 ); //0~5
hp-=at;
System.out.println(name + " 님이 " + at + " 데미지로 자해하고 있습니다. hp:" + hp);
}
System.out.println(name + " 님이 뒤졌습니다.");
}
public boolean isLive()
{
return hp >0;
}
}


아..글고,.. 런에이블 편하게 쓸라면...흠.. 멤버 필드로 Thread를 갖고.. 위임 패턴을 적용해볼까?  

class A 라면.. 런에이블 조립해서 run 재정의 하고.. 내부적으로 생성자에서 멤버 필드 스레드 객체를 생성할때.. this(자신)을 
매개변수로 넣으면 스레드는 이제 내 객체(a)를 참조할수 있으니.. start(){ thread.start(); } 처럼 간단하게 사용 가능할듯 .. 
=>문제는.. run()이 퍼블릭 인터페이스로 노출되는점 ㅠㅠ  사용자께서(나?) start()로 사용해 주시길..

public class ddd
{

public static void main(String[] args)
{
// TODO Auto-generated method stub
ChildA a = new ChildA();
ChildB b = new ChildB();
a.start();
b.start();

}

}

abstract class Base
{
protected Thread thread;
}

class ChildA extends Base implements Runnable
{
ChildA()
{
thread = new Thread(this);
}
@Override
public void run()
{
for(int i=0; i< 100; i++)
{
System.out.println(thread.getName());
}
}
public void start()
{
thread.start();
}
}

class ChildB extends Base implements Runnable
{
ChildB()
{
thread = new Thread(this);
}
@Override
public void run()
{
for(int i=0; i< 100; i++)
{
System.out.println(thread.getName());
}
}
public void start()
{
thread.start();
}
}


=>core api에서 제공하는 인터페이스의 사용에 대해 아주 쬐금 감을 잡은듯도 하다.. 상속을 받으면 유연하지 않으니.. 가급적
core api 의 경우 interface를 구현하고 해당 클래스를 멤버 필드로 갖자(상속보단 구성!)

아니면 말고.. 그만 놀고 공부하자  -_-;


ps.멀티 스레딩 관련 볼만한 책들.. 갖고 싶다..




by givingsheart 2014. 1. 1. 16:29