多线程优化资源占用过高

在实际的工程项目中肯定要经常用到多线程,如果多线程间用不好的情况下就会导致CPU占用过高甚至100%, 下面新建一个测试项目。

private void Form1_Load(object sender,EventArgs e)
{
    Thread th1,th2,th3,th4,th4;
    th1=new Thread(Thread1){IsBackGround=true};
    th2=new Thread(Thread2){IsBackGround=true};
    th3=new Thread(Thread3){IsBackGround=true};
    th4=new Thread(Thread4){IsBackGround=true};
    th5=new Thread(Thread5){IsBackGround=true};

    th1.Start();
    th2.Start();
    th3.Start();
    th4.Start();
    th5.Start();
}
private void Thread1()
{
    while(true);
}

private void Thread2()
{
    while(true);
}

private void Thread3()
{
    while(true);
}

private void Thread4()
{
    while(true);
}

private void Thread5()
{
    while(true);
}

运行以上5个线程的多线程,可以发现CPU的使用率就占到了100%

其实也有简单的处理办法就是在每个线程的循环中让其睡眠1ms就可以了。

private void Form1_Load(object sender,EventArgs e)
{
    Thread th1,th2,th3,th4,th4;
    th1=new Thread(Thread1){IsBackGround=true};
    th2=new Thread(Thread2){IsBackGround=true};
    th3=new Thread(Thread3){IsBackGround=true};
    th4=new Thread(Thread4){IsBackGround=true};
    th5=new Thread(Thread5){IsBackGround=true};

    th1.Start();
    th2.Start();
    th3.Start();
    th4.Start();
    th5.Start();
}
private void Thread1()
{
    while(true)
    Thread.Sleep(1);
}

private void Thread2()
{
    while(true)
    Thread.Sleep(1);
}

private void Thread3()
{
    while(true)
    Thread.Sleep(1);
}

private void Thread4()
{
    while(true)
    Thread.Sleep(1);
}

private void Thread5()
{
    while(true)
    Thread.Sleep(1);
}

转载请注明出处:  https://www.cntworld.cn
智能工控 » 多线程优化资源占用过高

发表回复

提供最优质的资源集合

立即查看 了解详情