2012-08-24 24 views
0

我怎样才能做一个while循环,每秒做不冻结应用程序的东西?例如使用Thread.Sleep()冻结线程。有人知道吗?无限虽然这不dlocking线程

+1

哪种语言? – Cdeez

+1

如果您从主线程调用睡眠,它将停止主线程。你需要创建另一个线程来完成工作。 – anio

回答

0

您没有指定语言。 我会在C++中提供一个示例,这个概念在其他语言中应该是相似的。

首先,这将使主线程睡眠:

int main(int, char**) 
{ 
    while(true) 
    { 
    sleep(1); // Put current thread to sleep; 
    // do some work. 

    } 
    return 0; 
} 

这在另一方面将创建一个工作线程。主线程将保持活动状态。

#include <iostream> 
#include <thread> 

void doWork() 
{ 
    while(true) 
    { 
     // Do some work; 
     sleep(1); // Rest 
     std::cout << "hi from worker." << std::endl; 
    } 
} 

int main(int, char**) 
{ 

    std::thread worker(&doWork); 
    std::cout << "hello from main thread, the worker thread is busy." << std::endl; 
    worker.join(); 

    return 0; 
} 

该代码未经测试。 刚刚经过测试,看到它在行动:http://ideone.com/aEVFi

需要C++ 11的线程。另外请注意,在上面的代码中,主线程将无限等待连接,因为工作线程永远不会终止。

0

将您的循环和Thread.Sleep()放入工作线程中。

1
public class Test implements Runnable { 

@Override 
public void run() { 
    while(true){ 
     try { 
      Thread.sleep(1000); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     // Your Statement goes here 

    } 

} 

public static void main(String[] args) { 
    Test test= new Test(); 
    Thread t= new Thread(test); 
    t.start(); 
} 

}