多线程编程学习笔记(五)

多线程编程学习笔记(五)
处理周期事件
1、System.WinForms.Timer
Timer的Tick事件代码:
Interlocked.Increment(ref _count);

2、ThreadPool
A.生成WaitOrTimerCallback事例
B.生成一个同步对象
C.添加到线程池

例1:
/*RegisterWaitForSingleObject
下面的示例演示了几种线程处理功能。

使用 RegisterWaitForSingleObject 将需要执行的任务以 ThreadPool 线程的方式排队。
使用 AutoResetEvent 发出信号,通知执行任务。
用 WaitOrTimerCallback 委托处理超时和信号。
用 RegisteredWaitHandle 取消排入队列的任务。
*/
using System;
using System.Threading;

// TaskInfo contains data that will be passed to the callback
// method.
public class TaskInfo {
    public RegisteredWaitHandle Handle = null;
    public string OtherInfo = "default";
}

public class Example {
    public static void Main(string[] args) {
        // The main thread uses AutoResetEvent to signal the
        // registered wait handle, which executes the callback
        // method.
        AutoResetEvent ev = new AutoResetEvent(false);

        TaskInfo ti = new TaskInfo();
        ti.OtherInfo = "First task";
        // The TaskInfo for the task includes the registered wait
        // handle returned by RegisterWaitForSingleObject.  This
        // allows the wait to be terminated when the object has
        // been signaled once (see WaitProc).
        ti.Handle = ThreadPool.RegisterWaitForSingleObject(
            ev,
            new WaitOrTimerCallback(WaitProc),
            ti,
            100,
            false
        );

        // The main thread waits three seconds, to demonstrate the
        // time-outs on the queued thread, and then signals.
        Thread.Sleep(3100);
        Console.WriteLine("Main thread signals.");
        ev.Set();

        // The main thread sleeps, which should give the callback
        // method time to execute.  If you comment out this line, the
        // program usually ends before the ThreadPool thread can execute.
        Thread.Sleep(1000);
        // If you start a thread yourself, you can wait for it to end
        // by calling Thread.Join.  This option is not available with
        // thread pool threads.
    }
  
    // The callback method executes when the registered wait times out,
    // or when the WaitHandle (in this case AutoResetEvent) is signaled.
    // WaitProc unregisters the WaitHandle the first time the event is
    // signaled.
    public static void WaitProc(object state, bool timedOut) {
        // The state object must be cast to the correct type, because the
        // signature of the WaitOrTimerCallback delegate specifies type
        // Object.
        TaskInfo ti = (TaskInfo) state;

        string cause = "TIMED OUT";
        if (!timedOut) {
            cause = "SIGNALED";
            // If the callback method executes because the WaitHandle is
            // signaled, stop future execution of the callback method
            // by unregistering the WaitHandle.
            if (ti.Handle != null)
                ti.Handle.Unregister(null);
        }

        Console.WriteLine("WaitProc( {0} ) executes on thread {1}; cause = {2}.",
            ti.OtherInfo,
            Thread.CurrentThread.GetHashCode().ToString(),
            cause
        );
    }
}

例2:
using System;
using System.Threading;

class State
{
 private int nCalledTimes = 0;
 public void Called()
 {
  Interlocked.Increment(ref nCalledTimes);
 }
 public int CalledTimes
 {
  get
  {
   return nCalledTimes;
  }
 }
}

class App
{
 static public void PeriodicMethod(object state , bool timeOut)
 {
  // timeOut为false时,说明等待有效,否则超时
  Console.WriteLine("/nThread {0}开始处理定时事件",Thread.CurrentThread.GetHashCode());
  if(!timeOut)
   Console.WriteLine("获得等待信号");
  else
   Console.WriteLine("超时事件发生");
  
  if(state!=null)
  {
   ((State)state).Called();
   Console.WriteLine("调用了{0}次",((State)state).CalledTimes);
  }
  Thread.Sleep(100);
  Console.WriteLine("Thread {0}处理定时事件完毕/n",Thread.CurrentThread.GetHashCode());
 }
 
 static public void Main()
 {
  AutoResetEvent myEvent = new AutoResetEvent(false);
  WaitOrTimerCallback waitOrTimerCallback = new WaitOrTimerCallback(App.PeriodicMethod);
  int timeout = 1000;
  bool executeOnlyOnce = false;
  
  State state = new State();
  
  ThreadPool.RegisterWaitForSingleObject(myEvent , waitOrTimerCallback , state ,timeout,executeOnlyOnce);
  //Thread.Sleep(10000);
  myEvent.Set();
  Console.WriteLine("按任意键退出");
  Console.ReadLine();
 }
}

3、System.Threading.Timer
A.实例化一个TimerCallback代理callback
B.创建一个System.Threading.Timer实例timer
C.如果有必要,调用 timer.Change重新设置timer的durTime和period
D.用timer.Dispose释放timer
using System;
using System.Threading;

class State
{
 private int threadID = -1;
 private AutoResetEvent firstTimerFired = null;
 public State(int threadID , AutoResetEvent firstTimerFired)
 {
  this.threadID = threadID;
  this.firstTimerFired = firstTimerFired;
 }
 
 public void Show()
 {
  Console.WriteLine("thread.HashCode={0}/tthreadID={1}在工作",Thread.CurrentThread.GetHashCode(),threadID);
 }
 
 public AutoResetEvent FirstTimerFired
 {
  get
  {
   return firstTimerFired;
  }
  set
  {
   firstTimerFired = value;
  }
 }
}

class App
{
 public static void Main()
 {
  Console.WriteLine("每2秒执行一次时钟事件");
  TimerCallback callback = new TimerCallback(App.CheckStatus);
  Timer timer1 = new Timer(callback , null ,1000 ,2000);
  AutoResetEvent firstTimerFired = new AutoResetEvent(false);
  State state = new State(2,firstTimerFired);
  
  Timer timer2 = new Timer(callback ,state , 5000 ,0);//定时器事件只触发一次,period为0
  firstTimerFired.WaitOne();
  
  Console.WriteLine("按回车继续...");
  Console.ReadLine();
  
  timer2.Change(2000,1000);
  Console.WriteLine("按回车继续...");
  Console.ReadLine();
  
  timer1.Dispose();
  timer2.Dispose();
 }
 
 static void CheckStatus(object state)
 {
  if (state !=null)
  {
   ((State)state).Show();
   if(((State)state).FirstTimerFired != null)
    ((State)state).FirstTimerFired.Set();
  }
  else
  {
   Console.WriteLine("tread.HashCode = {0}/tthreadID={1}在工作",Thread.CurrentThread.GetHashCode(),-1);
  }
 }
}

4、System.Timers.Timer
基于服务器的计时器的关键编程元素
Timer 组件引发一个名为 Timer.Elapsed 的事件。您可以为这个事件创建处理程序来执行处理要发生的一切。

Timer 组件的一些更重要的属性和方法还包含:

Interval 属性用来设置引发事件的时间范围,以毫秒计。例如,值为 1000 的时间间隔将一秒钟引发一次事件。
AutoReset 属性决定在给定时间间隔过去之后计时器是否继续引发事件。如果设置成 true,计时器继续重新计算时间间隔并引发事件。如果为 false,它在时间间隔过去后只引发一次事件,然后停止。
Start 方法将计时器的 Enabled 属性设置为 true,它允许计时器开始引发事件。如果计时器已经是启用状态,则调用 Start 方法将重置该计时器。
Stop 方法将计时器的 Enabled 属性设置成 false,以防止计时器再引发事件。
A.创建System.Timers.Timer对象kicker
B.设置周期
C.设置AutoReset为true
D.设置kicker的Elapsed事件
E.启动kicker
F.如果需要,可以重新设置kicker的Interval属性
G.停止记时器
using System;
using System.Timers;
using System.Threading;

class App
{
 private static DateTime stopTime = new DateTime(2005,4,2);
 static void ElapsedHandler(object sender , ElapsedEventArgs e)
 {
  if (DateTime.Compare(e.SignalTime , stopTime) > 0 )
  {
   Console.WriteLine("Thread {0} 处理定事事件",Thread.CurrentThread.GetHashCode());
   Thread.Sleep(100);
  }
 }
 
 static public void Main()
 {
  System.Timers.Timer kicker = new System.Timers.Timer();
  kicker.Interval =1000;
  kicker.AutoReset = true;
  kicker.Elapsed += new ElapsedEventHandler(ElapsedHandler);
  kicker.Start();
  Thread.Sleep(2100);
  Console.WriteLine("改变时间间隔");
  kicker.Interval = 2000;
  Thread.Sleep(2100);
  Console.WriteLine("结束定事器");
  //kicker.Stop();
  stopTime = DateTime.Now;
  Thread.Sleep(2100);
  Console.WriteLine("重新启动定事器");
  kicker.Start();
  Thread.Sleep(8100);
  Console.WriteLine("按任意键退出");
  //Console.ReadLine();
  //Thread.Sleep(14100);
  kicker.Stop();
  stopTime = DateTime.Now;
 }
}

System.Winforms.Timer、System.Threading.Timer、System.Timers.Timer,通过设置定时周期、定时事件、可以启动、终止、再启动定时器、重新设置定时器属性等。功能依次增强。
ThreadPool一旦设置好时钟属性并启动后,就不能对定时器进行控制。
《.net核心技术-原理与架构》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是Java多线程编程学习笔记之十二:生产者—消费者模型的相关内容和代码。 ## 生产者—消费者模型简介 生产者—消费者模型是一种常见的多线程并发模型,它涉及到两个角色:生产者和消费者。生产者负责生产数据,消费者负责消费数据。生产者和消费者通过一个共享的缓冲区进行通信,生产者将数据放入缓冲区,消费者从缓冲区获取数据。 在多线程编程中,生产者—消费者模型的实现有多种方式,本文将介绍一种基于Java的实现方式。 ## 生产者—消费者模型的实现 ### 1. 定义共享缓冲区 共享缓冲区是生产者和消费者进行通信的桥梁,它需要实现以下功能: - 提供一个put方法,允许生产者将数据放入缓冲区; - 提供一个take方法,允许消费者从缓冲区获取数据; - 当缓冲区已满时,put方法应该等待; - 当缓冲区为空时,take方法应该等待。 以下是一个简单的共享缓冲区的实现: ```java public class Buffer { private int[] data; private int size; private int count; private int putIndex; private int takeIndex; public Buffer(int size) { this.data = new int[size]; this.size = size; this.count = 0; this.putIndex = 0; this.takeIndex = 0; } public synchronized void put(int value) throws InterruptedException { while (count == size) { wait(); } data[putIndex] = value; putIndex = (putIndex + 1) % size; count++; notifyAll(); } public synchronized int take() throws InterruptedException { while (count == 0) { wait(); } int value = data[takeIndex]; takeIndex = (takeIndex + 1) % size; count--; notifyAll(); return value; } } ``` 上面的Buffer类使用一个数组来表示缓冲区,size表示缓冲区的大小,count表示当前缓冲区中的元素数量,putIndex和takeIndex分别表示下一个可写和可读的位置。put和take方法都是同步方法,使用wait和notifyAll来进行线程间的等待和通知。 ### 2. 定义生产者和消费者 生产者和消费者都需要访问共享缓冲区,因此它们都需要接收一个Buffer对象作为参数。以下是生产者和消费者的简单实现: ```java public class Producer implements Runnable { private Buffer buffer; public Producer(Buffer buffer) { this.buffer = buffer; } public void run() { try { for (int i = 0; i < 10; i++) { buffer.put(i); System.out.println("Produced: " + i); Thread.sleep((int)(Math.random() * 1000)); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class Consumer implements Runnable { private Buffer buffer; public Consumer(Buffer buffer) { this.buffer = buffer; } public void run() { try { for (int i = 0; i < 10; i++) { int value = buffer.take(); System.out.println("Consumed: " + value); Thread.sleep((int)(Math.random() * 1000)); } } catch (InterruptedException e) { e.printStackTrace(); } } } ``` 生产者在一个循环中不断地向缓冲区中放入数据,消费者也在一个循环中不断地从缓冲区中获取数据。注意,当缓冲区已满时,生产者会进入等待状态;当缓冲区为空时,消费者会进入等待状态。 ### 3. 测试 最后,我们可以使用下面的代码来进行测试: ```java public class Main { public static void main(String[] args) { Buffer buffer = new Buffer(5); Producer producer = new Producer(buffer); Consumer consumer = new Consumer(buffer); Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); } } ``` 在上面的代码中,我们创建了一个缓冲区对象和一个生产者对象和一个消费者对象,然后将它们分别传递给两个线程,并启动这两个线程。 运行上面的代码,我们可以看到生产者和消费者交替地进行操作,生产者不断地向缓冲区中放入数据,消费者不断地从缓冲区中获取数据。如果缓冲区已满或者为空,生产者和消费者会进入等待状态,直到缓冲区中有足够的空间或者有新的数据可用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值