zoukankan      html  css  js  c++  java
  • C#語法學習線程(Thread)

    /*
     * Created by SharpDevelop.
     * User: Administrator
     * Date: 2008/9/11
     * Time: 下午 02:36
     * 
     
    */
    using System;
    using System.Threading;
    class SingleThread
    {
        
    static void Main(string [] args)
        {
            SingleThread st 
    =new SingleThread();
            Thread th 
    =new Thread(new ThreadStart(st.SayHello));
            th.Start();
        }
        
    public void SayHello()
        {
            Console.WriteLine(
    "Hello from a single thread.");
        }
    }

    /*
     * Created by SharpDevelop.
     * User: Administrator
     * Date: 2008/9/11
     * Time: 下午 02:41
     * 
     
    */

    using System;
    using System.Threading;
    class SyncData
    {
        
    int index=0;
        
    string[] comment=new string[]{"","","","","","","","","","","十一","十二","十三","十四","十五","十六","十七","十八","十九","二十"}; 
        
    public string GetNetComment()
        {
            
    lock(this)
            {
                
    if(index<comment.Length)
                {
                    
    return comment[index++];
                }
                
    else
                {
                    
    return "empty";
                }
            }
        }
    }
    class Synchronization
    {
        SyncData sdat
    =new SyncData();
        
    public void GetComments()
        {
            
    string comment;
            
    do
            {
                comment
    =sdat.GetNetComment();
                Console.WriteLine(
    "Current Thread:{0},comment:{1}",Thread.CurrentThread.Name,comment);
            }
    while(comment!="empty");
        }
        
        
    static void Main(string[] args)
        {
            Synchronization sync
    =new Synchronization();
            Thread t1
    =new Thread(new ThreadStart(sync.GetComments));
            Thread t2
    =new Thread(new ThreadStart(sync.GetComments));
            Thread t3
    =new Thread(new ThreadStart(sync.GetComments));
            t1.Name
    ="Thread 1";
            t2.Name
    ="Thread 2";
            t3.Name
    ="Thread 3";
            t1.Start();
            t2.Start();
            t3.Start();
        }
    }

    申明

    非源创博文中的内容均收集自网上,若有侵权之处,请及时联络,我会在第一时间内删除.再次说声抱歉!!!

    博文欢迎转载,但请给出原文连接。

  • 相关阅读:
    496. 下一个更大元素 I『简单』
    492. 构造矩形『简单』
    443. 压缩字符串『简单』
    455. 分发饼干『简单』
    463. 岛屿的周长『简单』
    38. 外观数列『简单』
    28. 实现 strStr()『简单』
    441. 排列硬币『简单』
    628. 三个数的最大乘积『简单』
    575. 分糖果『简单』
  • 原文地址:https://www.cnblogs.com/Athrun/p/1289128.html
Copyright © 2011-2022 走看看