java线程如何关闭
1、打开eclipse软件,如图所示:
2、点击菜单栏New-->Java Project,如图所示:
3、新建java项目成功之后,新建一个线程类,
如图所示:
4、在新建线程类中键入如下代码:
package com.tang.java.demo;
public class ThreadDemo {
public static void main(String[] args) {
new NewThread(); // 创建一个新线程
try {
for(int i = 5; i > 0; i--) {
System.out.println("主线程: " + i);
//线程停止100毫秒
Thread.sleep(100);
//停止线程方法
Thread.interrupted();
}
} catch (InterruptedException e) {
System.out.println("主线程中止.");
}
System.out.println("主线程退出.");
}
}
//创建一个新的线程
class NewThread implements Runnable {
Thread t;
NewThread() {
// 创建第二个新线程
t = new Thread(this, "Demo Thread");
System.out.println("子线程 thread: " + t);
t.start(); // 开始线程
}
// 第二个线程入口
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("子线程 Thread: " + i);
// 暂停线程
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("子线程 interrupted.");
}
System.out.println("子线程退出 thread.");
}
}
5、然后点击运行,Run-->Run as-->Java Application