0326 스레드

2021. 3. 26. 17:00C#/수업내용

닷넷에서 스레드는 작업자 한 명을 나타낸다.

다중 스레드는 여러 작업자를 두고 동시에 여러 작업을 처리하는 것을 뜻한다.

 

프로세서: 현재 실행 중인 프로그램

스레드: 프로그램이 실행하는 데 필요한 메모리 기본 단위

 

ThreadStart 대리자를 사용한다.

public delegate void ThreadStart();

스레드는 스레드에 담을 메서드를 여러 개 구현해 놓고 이를 스레드스타트 대리자에 등록한다.

 

priority: 스레드의 우선순위를 결정 Highest, normal, lowest

abort: 스레드 종료

sleep: 스레드 밀리초만큼 중지

start: 스레드 시작

 

Process.Start 클래스 : 로컬 프로그램을 강제적으로 실행 가능

lock문 : 다른 스레드가 접근하지 못하게 막아버린다.

 

using System;
using System.Diagnostics;
using System.Threading;

namespace ConsoleApp14
{
    public class App
    {
        public App() 
        {
            Thread t1 = new Thread(this.Idle);
            Thread t2 = new Thread(this.Sql);
            Thread t3 = new Thread(this.Win)
            {
                Priority = ThreadPriority.Highest
            };

            t1.Start();
            t2.Start();
            t3.Start();

            Process.Start("chrome.exe");
            Process.Start("notepad.exe");
        }
        private void Idle() 
        {
            Thread.Sleep(1000);
            Console.WriteLine("비주얼 스튜디오를 실행합니다.");
        }
        private void Win()
        {
            Thread.Sleep(1000);
            Console.WriteLine("윈도우 서버에 접속합니다.");
        }
        private void Sql()
        {
            Thread.Sleep(1000);
            Console.WriteLine("DB 서버에 접속합니다.");
        }
    }
}

 

Abort() 사용

public class App
    {
        public App() 
        {
            Thread t = new Thread(new ThreadStart(this.testMethod));
            t.Start();
            Thread.Sleep(1000);

            //Abort thread
            Console.WriteLine("Main aborting new thread");
            t.Abort("Information from Main");
        }
        private void testMethod()
        {
            try
            {
                while (true)
                {
                    Console.WriteLine("New thread running");
                    Thread.Sleep(1000);
                }
            }
            catch (ThreadAbortException abortException) 
            {
                Console.WriteLine((string)abortException.ExceptionState);
            }
        }
    }

 

 

public class Customer
    {
        public string name;
        public Account account;
        public object lockobj = new object();
        
        public Customer(string name,Account account) 
        {
            this.name = name;
            this.account = account;
        }
        public void Withdraw(int amount)
        {
            for (int i = 0; i < 10; i++) 
            {
                Thread t = new Thread(new ThreadStart(() =>
                {
                    lock (lockobj) {
                        Thread.Sleep(1000);
                        this.account.balance -= amount;
                        Console.WriteLine("{0}, {1}", this.name, this.account.balance);
                    }
                }));
                t.Start();
            }
        }
    }
public class Account
    {
        public int balance;
        public Account(int balance) 
        {
            this.balance = balance;
        }
    }
public class App
    {
        public App() 
        {
            Account account = new Account(10000);
            Console.WriteLine(account.balance);

            Customer customer1 = new Customer("홍길동", account);
            Customer customer2 = new Customer("임꺽정", account);

            customer1.Withdraw(100);
            customer2.Withdraw(100);
        }
    }

 

 

public class App
    {
        public App() 
        {
            Thread t1 = new Thread(new ThreadStart(this.Work));
            t1.Name = "sub";
            t1.Start();

            Console.WriteLine("t1 state: {0}", t1.ThreadState);

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("main: {0}", i);
                Thread.Sleep(1000);
            }

        }
        private void Work() 
        {
            for (int i = 0; i < 10; i++) 
            {
                Console.WriteLine("Work: {0}", i);
                Thread.Sleep(1000);
            }
        }
    }

'C# > 수업내용' 카테고리의 다른 글

0329 Task/async/await  (0) 2021.03.29
0326 쿠키런 직렬화/역직렬화  (0) 2021.03.26
0325 싱글턴 패턴  (0) 2021.03.25
0324 File 클래스 (외부 파일 불러오기)  (0) 2021.03.24
0324 복습  (0) 2021.03.24