즐겁게 하하하 2022. 4. 13. 18:04
728x90

Thread풀이란 재사용이 가능한 자원을 빠르게 할당하기위해 미리 준비된 공간입니다.

스레드를 만들어서 처리하는 것과 비슷하지만 생성, 소멸의 비용이 최소화됐다는 차이점이 있습니다.

 

new Thread( new ThreadStart(Run) );  ## ThreadStart는 파라메터를 전달하지 않습니다.

using System.Threading;
namespace ConEx06
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread t1 = new Thread(new ThreadStart(Run));    //델리게이트 타입으로 전달
            t1.Start();
        }

		//실행할 함수
        public static void Run()
        {
            for(int i=0; i<10; i++)
            {
                Thread.Sleep(500);
                Console.WriteLine("ex: {0}", i);
            }
        }
        
    }
}

 

new Thread( new ParameterizedThreadStart(Square) );  ## Thread클래스에 파라메터 전달

namespace ConEx06
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread t1 = new Thread(new ParameterizedThreadStart(Square));
            t1.Start(20.0);
            Thread t2 = new Thread(() => Sum(100, 100, 100));            //람다식 이용해서 전달할수도...
            t2.Start();
        }

        static void Square(object num)    // 기본적으로 object로 전달
        {
            double res = (double)num * (double)num;
            Console.WriteLine("Num: {0}, Square: {1}", (double)num, res);    
        }

        static void Sum(int n1, int n2, int n3)
        {
            int res = n1 + n2 + n3;
            Console.WriteLine(res);
        }
        
    }
}

 

백그라운드와 Foreground 쓰레드의 기본적인 차이점은 Foreground 쓰레드는 메인 쓰레드가 종료되더라도 Foreground 쓰레드가 살아 있는 한, 프로세스가 종료되지 않고 계속 실행되고, 백그라운드 쓰레드는 메인 쓰레드가 종료되면 바로 프로세스를 종료한다는 점이다.

// Foreground 쓰레드
Thread t1 = new Thread(new ThreadStart(Run));            
t1.Start();
            
// 백그라운드 쓰레드
Thread t2 = new Thread(new ThreadStart(Run));
t2.IsBackground = true;
t2.Start();

 


// Fax 전송  Thread 처리
FaThread faThread = new FaThread(faxMap , files.getSaveFle() , sftpDir);
faThread.start();
try {
    faThread.join(10000);
} catch (InterruptedException e) {
    //e.printStackTrace();
    log.info("Error 가 발생되었습니다");
} catch(Exception e) {
    log.info("Error 가 발생되었습니다");
}
faxThread.interrupt();
public class FaThread extends Thread{

    static Search faMap = new Search();

    static String saveFle;
    static String sftpDir;

    public EaiFaxThread(Search faMap , String saveFle , String sftpDir) {
        this.faMap = faMap;
        this.saveFle = saveFle;
        this.sftpDir = sftpDir;
    }

    // 스레드로 수행할 메소드
    public void run() {
        try{
            synchronized(faMap) {
                System.out.println("===============================");
                System.out.println("Thread  시작 : " + faMap.get("ADDR"));
                // DB insert 를 위한 param 세팅
                String sftpUrl = ConfigProperty.getString("mci.sftp.ip");
                String sftpUser = ConfigProperty.getString("mci.sftp.id");
                String sftpPassword = ConfigProperty.getString("mci.sftp.pw");
                SFTPUtil.init(sftpUrl, sftpUser, sftpPassword); // EAI connect

                // 서버에 저장된 파일을 불러온다.
                File sftpFile = new File( ConfigProperty.getString("upload.path") + ConfigProperty.getString("faxOriginalFile.path") + "/" + saveFle );
                SFTPUtil.upload( sftpDir,  sftpFile );

                String rslt = HttpUtil.callPostMci(faMap);
                SFTPUtil.disconnect(); // 연결 종료
                System.out.println("Thread 종료 : " + faMap.get("ADDR"));
                System.out.println("===============================");
            }
        } catch(Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println("Thread is dead...");
        }
    }
}

 

 

import java.util.concurrent.Semaphore;

public class testMain {

	private static final Semaphore semaphore = new Semaphore(1);

    public static void processSftpFiles() {
        // SFTP 접속 및 파일 목록 가져오는 로직
        // ...

        try {
            semaphore.acquire(); // 세마포어 획득
             
            System.out.println("============== 진행중 ");
            Thread.sleep(9000);
            
            
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            semaphore.release(); // 세마포어 반환
            System.out.println("============== 끝 ");
        }
    }

    public static void main(String[] args) {
        // 두 개의 스레드가 동시에 호출
        Thread thread1 = new Thread(() -> {
        	testMain aa1 = new testMain();
            aa1.processSftpFiles();
        });
        
        

        Thread thread2 = new Thread(() -> {
        	testMain aa2 = new testMain();
            aa2.processSftpFiles();
        });
        
        

        thread1.start();
        System.out.println(thread1.getName()); 
        
        thread2.start();
        System.out.println(thread2.getName()); 
    }

}
728x90