java让一个线程一直运行。java代码

public class MyThread{
	
	public static void Thread(){	
		new Thread() {
			int i = 0;
			public void run(){
			boolean flg = false;	
			while(!flg){				
				try {
					i++;
					System.out.println("我是"+i);
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}	
		}
		}.start();
	}
	
	public static void main(String[] args) {
		Thread();
	}
}

下面是控制台输出的代码

java让一个线程一直运行。java代码

 在线程中写一个死循环  ,线程就可以一直运行,里面在加一个sleep() 方法  就能让他每隔多长时间运行一次。