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();
        }
    }

    申明

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

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

  • 相关阅读:
    Apache Tomcat 6.0 Tomcat6 服务因 1 (0x1) 服务特定错误而停止
    PaodingAnalysis 提示 "dic home should not be a file, but a directory"
    mappingDirectoryLocations
    多级反向代理下,Java获取请求客户端的真实IP地址多中方法整合
    java.util.ResourceBundle
    JSP验证码
    Error: [ng:areq] Argument 'LoginCtrl' is not a function, got undefined
    《横向领导力》笔记
    Java执行定时任务
    2017第43周三
  • 原文地址:https://www.cnblogs.com/Athrun/p/1289128.html
Copyright © 2011-2022 走看看