您现在的位置: 365建站网 > 365文章 > C#/vb.net/java暂停线程和恢复的实现方法

C#/vb.net/java暂停线程和恢复的实现方法

文章来源:365jz.com     点击数:784    更新时间:2019-06-18 11:14   参与评论

C#暂停线程和恢复的实现方法:

.NET 基础类库的System.Threading命名空间提供了大量的类和接口支持多线程。这个命名空间有很多的类。System.Threading.Thread类是创建并控制线程,设置其优先级并获取其状态最为常用的类。他有很多的方法,在这里我们将就比较常用和重要的方法做一下介绍:
    Thread.Start():启动线程的执行;

  Thread.Suspend():挂起线程,或者如果线程已挂起,则不起作用;

  Thread.Resume():继续已挂起的线程;

  Thread.Interrupt():中止处于 Wait或者Sleep或者Join 线程状态的线程;

  Thread.Join():阻塞调用线程,直到某个线程终止时为止

  Thread.Sleep():将当前线程阻塞指定的毫秒数;

  Thread.Abort():以开始终止此线程的过程。如果线程已经在终止,则不能通过Thread.Start()来启动线程。



</>code

  1. private void GetBidList()
  2.                 {
  3.                         Console.WriteLine("-----------www.itsvse.com------");
  4.                         while (true)
  5.                         {
  6.                                 Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
  7.                                 Thread.Sleep(1000);
  8.                         }
  9.                 }
  10.                 private void button1_Click(object sender, EventArgs e)
  11.                 {
  12.                         if (GET_LIST.ThreadState == (ThreadState.Suspended | ThreadState.Background))
  13.                         {
  14.                                 GET_LIST.Resume();
  15.                                 Console.WriteLine("线程继续");
  16.                         }
  17.                         else
  18.                         {
  19.                                 GET_LIST.Start();
  20.                                 Console.WriteLine("线程开始");
  21.                         }
  22.                 }
  23.                 private void button2_Click(object sender, EventArgs e)
  24.                 {
  25.                         GET_LIST.Suspend();
  26.                         Console.WriteLine("线程挂起");
  27.                 }
  28.                 private void Form1_Load(object sender, EventArgs e)
  29.                 {
  30.                         GET_LIST = new Thread(new ThreadStart(GetBidList)) { IsBackground = true };
  31.                 }


另外我们可以通过ManualResetEvent类来实现。

声明, 初始化时不执行

private static ManualResetEvent _eventWorkList = new ManualResetEvent(false);


Thead里的信号等待, 放在要控制的线程内, 当外部调用Reset时,线程暂停;当外部调用Set时,线程继续执行;


_eventWorkList.WaitOne();



暂停线程

             // Pause the WorkList operation.

            _eventWorkList.Reset();


恢复线程


            // Resume WorkList

            _eventWorkList.Set();


</>code

  1. using System;
  2. using System.Text;
  3. using System.Windows.Forms;
  4. using System.Threading;
  5.  
  6. namespace WindowsApplication1
  7. {
  8.     public partial class Form1 : Form
  9.     {
  10.         public Form1()
  11.         {
  12.             InitializeComponent();
  13.         }
  14.  
  15.         private void button1_Click(object sender, EventArgs e)
  16.         {
  17.             Thread th = new Thread(YourThread);
  18.             th.Start();
  19.         }
  20.  
  21.         private void textBox1_TextChanged(object sender, EventArgs e)
  22.         {
  23.             if (textBox1.Text.Length >= 4)
  24.             {
  25.                 detailCollectedEvent.Set();                      // 当textBox1的文本超过4位,发一个通知
  26.             }
  27.         }
  28.  
  29.         AutoResetEvent detailCollectedEvent = new AutoResetEvent(false);
  30.         void YourThread()
  31.         {
  32.             MessageBox.Show("input you bank account details into the textbox");
  33.             detailCollectedEvent.WaitOne();                      // 等候通知
  34.             MessageBox.Show("we will keep the secret.");
  35.         }
  36.     }
  37. }


java 线程的开始、暂停、继续

  Android项目中的一个需求:通过线程读取文件内容,并且可以控制线程的开始、暂停、继续,来控制读文件。在此记录下。


  直接在主线程中,通过wait、notify、notifyAll去控制读文件的线程(子线程),报错:java.lang.IllegalMonitorStateException。


  需要注意的几个问题:


    1.任何一个时刻,对象的控制权(monitor)只能被一个线程拥有。


    2.无论是执行对象的wait、notify还是notifyAll方法,必须保证当前运行的线程取得了该对象的控制权(monitor)。


    3.如果在没有控制权的线程里执行对象的以上三种方法,就会报错java.lang.IllegalMonitorStateException。


    4.JVM基于多线程,默认情况下不能保证运行时线程的时序性。


  线程取得控制权的3种方法:


    1.执行对象的某个同步实例方法。


    2.执行对象对应类的同步静态方法。


    3.执行对该对象加同步锁的同步块。


  这里将开始、暂停、继续封装在线程类中,直接调用该实例的方法就行。


</>code

  1. public class ReadThread implements Runnable{
  2.         public Thread t;
  3.         private String threadName;
  4.         boolean suspended=false;
  5.         
  6.         public ReadThread(String threadName){
  7.             this.threadName=threadName;
  8.             System.out.println("Creating " +  threadName );
  9.         }
  10.         public void run() {
  11.           for(int i = 10; i > 0; i--) {
  12.             System.out.println("Thread: " + threadName + ", " + i);
  13.             // Let the thread sleep for a while.
  14.             try {
  15.                 Thread.sleep(300);
  16.                 synchronized(this) {
  17.                     while(suspended) {
  18.                        wait();
  19.                     }
  20.                 }
  21.             } catch (InterruptedException e) {
  22.                 System.out.println("Thread " +  threadName + " interrupted.");
  23.                 e.printStackTrace();
  24.             }
  25.             System.out.println("Thread " +  threadName + " exiting.");
  26.           }
  27.         }
  28.         
  29.         /**
  30.          * 开始
  31.          */
  32.         public void start(){
  33.             System.out.println("Starting " +  threadName );
  34.             if(t==null){
  35.                 t=new Thread(this, threadName);
  36.                 t.start();
  37.             }
  38.         }
  39.         
  40.         /**
  41.          * 暂停
  42.          */
  43.          void suspend(){
  44.             suspended = true;
  45.         }
  46.          
  47.          /**
  48.           * 继续
  49.           */
  50.          synchronized void resume(){
  51.              suspended = false;
  52.              notify();
  53.          }
  54.     }


如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (784人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号