○スレッドの生成

using System;

class Class1
{
	static void Main(string[] args)
	{
		Class1 obj=new Class1();
	}

	public Class1()
	{
		System.Threading.Thread t1=new System.Threading.Thread(new System.Threading.ThreadStart(this.thread1));
		System.Threading.Thread t2=new System.Threading.Thread(new System.Threading.ThreadStart(this.thread2));
		t1.Start();
		t2.Start();
		
		Console.Read();
	}

	private void thread1()
	{
		print("thread1");
	}

	private void thread2()
	{
		print("thread2");
	}

	private void print(String str)
	{
		for(int i=0;i<5;i++)
		{
			System.Threading.Thread.Sleep(100);
			Console.WriteLine(str);
		}
	}
}

処理結果
thread1
thread2
thread1
thread2
thread1
thread2
thread1
thread2
thread1
thread2

○クリティカルセッション
上のプログラムを変更します

	private void print(String str)
	{
		lock(typeof(Class1))
		{
			for(int i=0;i<5;i++)
			{
				System.Threading.Thread.Sleep(100);
				Console.WriteLine(str);
			}
		}
	}

処理結果
thread1
thread1
thread1
thread1
thread1
thread2
thread2
thread2
thread2
thread2


○一定時間後にスレッドを殺す

class Program
{
    static void Main(string[] args)
    {
        Program obj = new Program();
    }

    public Program()
    {
        System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(this.func));
        th.Start();
        //th.Join();
        //1秒間終了を待機して
        th.Join(1000);
        //スレッドを殺す
        th.Abort();
        System.Console.Read();
    }
    private void func()
    {
        while (true)
        {
            System.Threading.Thread.Sleep(100);
            System.Console.WriteLine("test");
        }
    }
}






▲トップページ > Visual BASIC と C#