用Java写一个线程

daisy185756828 2009-03-11 04:43:11
写一个线程(包括如何停止一个线程)
...全文
76 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
csouyangjun 2009-03-11
  • 打赏
  • 举报
回复
继承 Thread类 或 实现 Runnable

重写里面的 run 方法
ZiSheng 2009-03-11
  • 打赏
  • 举报
回复
在控制台输入 stop 即停止该线程
ZiSheng 2009-03-11
  • 打赏
  • 举报
回复

public class Test extends Thread {
private String name;

public Test(String name) {
this.name = name;
}

public void write() {
System.out.print(name);
}

public static void main(String[]args) throws Exception{
Thread t1=new Test("myThread");
t1.start();
Scanner sc=new Scanner(System.in);
String s;
while((s=sc.next()).equals("stop")){
t1.interrupt();
break;
}
}


public void run() {
for(int i=0;;i++){
if(this.isInterrupted()){
System.out.println("exit*****************");
return;
}
write();
System.out.println();

}
}

}
Sou2012 2009-03-11
  • 打赏
  • 举报
回复
实现Runnable接口或是继承Thread类

停止有好多方式,楼主不自己写么

81,091

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧