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

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

文章来源:365jz.com     点击数:736    更新时间: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()来启动线程。



private void GetBidList()
                {
                        Console.WriteLine("-----------www.itsvse.com------");
                        while (true)
                        {
                                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
                                Thread.Sleep(1000);
                        }
                }
                private void button1_Click(object sender, EventArgs e)
                {
                        if (GET_LIST.ThreadState == (ThreadState.Suspended | ThreadState.Background))
                        {
                                GET_LIST.Resume();
                                Console.WriteLine("线程继续");
                        }
                        else
                        {
                                GET_LIST.Start();
                                Console.WriteLine("线程开始");
                        }
                }
                private void button2_Click(object sender, EventArgs e)
                {
                        GET_LIST.Suspend();
                        Console.WriteLine("线程挂起");
                }
                private void Form1_Load(object sender, EventArgs e)
                {
                        GET_LIST = new Thread(new ThreadStart(GetBidList)) { IsBackground = true };
                }


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

声明, 初始化时不执行

private static ManualResetEvent _eventWorkList = new ManualResetEvent(false);


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


_eventWorkList.WaitOne();



暂停线程

             // Pause the WorkList operation.

            _eventWorkList.Reset();


恢复线程


            // Resume WorkList

            _eventWorkList.Set();


using System;
using System.Text;
using System.Windows.Forms;
using System.Threading;
 
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(YourThread);
            th.Start();
        }
 
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text.Length >= 4)
            {
                detailCollectedEvent.Set();                      // 当textBox1的文本超过4位,发一个通知
            }
        }
 
        AutoResetEvent detailCollectedEvent = new AutoResetEvent(false);
        void YourThread()
        {
            MessageBox.Show("input you bank account details into the textbox");
            detailCollectedEvent.WaitOne();                      // 等候通知
            MessageBox.Show("we will keep the secret.");
        }
    }
}


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.执行对该对象加同步锁的同步块。


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


public class ReadThread implements Runnable{
        public Thread t;
        private String threadName;
        boolean suspended=false;
        
        public ReadThread(String threadName){
            this.threadName=threadName;
            System.out.println("Creating " +  threadName );
        }
        public void run() {
          for(int i = 10; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
            // Let the thread sleep for a while.
            try {
                Thread.sleep(300);
                synchronized(this) {
                    while(suspended) {
                       wait();
                    }
                }
            } catch (InterruptedException e) {
                System.out.println("Thread " +  threadName + " interrupted.");
                e.printStackTrace();
            }
            System.out.println("Thread " +  threadName + " exiting.");
          }
        }
        
        /**
         * 开始
         */
        public void start(){
            System.out.println("Starting " +  threadName );
            if(t==null){
                t=new Thread(this, threadName);
                t.start();
            }
        }
        
        /**
         * 暂停
         */
         void suspend(){
            suspended = true;
        }
         
         /**
          * 继续
          */
         synchronized void resume(){
             suspended = false;
             notify();
         }
    }


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

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

快速入口

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

其它栏目

· 建站教程
· 365学习

业务咨询

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

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

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