티스토리 뷰

java thread 상태 check해서 없으면 생성하는 로직
 
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class ThreadManageTest {
    static private HashMap<Long, Thread> threadHashMap = new HashMap<>();

    public static void main(String[] args) throws InterruptedException {
        ThreadManageTest threadManageTest = new ThreadManageTest();
        Thread thread = threadManageTest.threadMaker(new Game(30l, "progress"));
        thread.start();

        threadHashMap.put(30l, thread);

        while(true){
            System.out.println("running");
            threadManageTest.processRun();
            Thread.sleep(5000);
        }
    }

    public void processRun(){
        List<Game> games = new ArrayList<>();
        games.add(new Game(10l, "progress"));
        games.add(new Game(20l, "progress"));

        // select되지 않은애는 없앤다.
        games = null;

        notSelectedList(games).forEach(id ->{
            System.out.format("%s", threadHashMap.size());
            threadHashMap.remove(id);
        });


        games.forEach((game)->{
            System.out.format("- hmSize:%s, key:%s %s \n",threadHashMap.size(), game, threadHashMap.get(game.id));
            if(threadHashMap.get(game.id) == null){
                System.out.format("-%s is null \n", game.id);
                Thread thread = threadMaker(game);
                thread.start();
                threadHashMap.put(game.id, thread);
            }else{
                System.out.println("thread already exist");
            }
        });

    }

    private List<Long> notSelectedList(List<Game> games){
        // games에는 없는데 threadHashMap에는 있는것들
        List<Long> idList = games.stream().map(game -> game.getId()).collect(Collectors.toList());
        idList.add(30l);

        return idList;
    }

    public Thread threadMaker(Game game){
        return new Thread(() ->{
            while(true){
                System.out.format("-thread id:%s, hashCode:%s \n", game.id, this.hashCode());
                System.out.println("http request");
                System.out.println("parsing");
                System.out.println("save");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}

@Data
class Game{
    long id;
    String status;

    public Game(long id, String status) {
        this.id = id;
        this.status = status;
    }
}
 
thread hashmap에 넣고 해당 key값 있는지 check해서 없으면 생성하는 로직
 
threadHashMap은 static으로 선언 한다.

 

end.

 

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함