高分求教:线程方法

xroll 2003-04-10 08:45:18
最近编得很烦,书上讲得不清楚,清高手指点线程中的方法。特别是:join(),还有stop();不主张使用,那用什么方法来结束线程;
...全文
13 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
cowboy1114 2003-04-14
  • 打赏
  • 举报
回复
public class JoinThread
implements Runnable
{

public JoinThread()
{
a=new Thread(this);
System.out.println("线程a创建");

}

public static void main(String[] args)
{
JoinThread j=new JoinThread();

j.a.start();
System.out.println("线程a运行");
try
{
j.a.join(); //等待a运行完
}
catch(InterruptedException e)
{
System.out.println("some thing interrputed");
}

System.out.println("线程b运行");
j.b.start(); //a运行完后,b启动开始
}

public void run()
{

System.out.println("线程处理开始(模拟事务)");
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("some thing interrputed");
}

//如果b还没建立的话
if(b==null)
{
b=new Thread(this);
System.out.println("线程b创建");
}

}

Thread a=null;
Thread b=null;
}
//不懂再找我
qnzu 2003-04-11
  • 打赏
  • 举报
回复
你也可以在线程中设置一个信号量,当一定条件下,线程自己结束循环。
cloudtarget 2003-04-11
  • 打赏
  • 举报
回复
直接赋值为null也可
cowboy1114 2003-04-11
  • 打赏
  • 举报
回复
//比较安全的做法是运用interrupt()来打断线程的运行,我在下面举个例子说明:

public class Gm extends Thread
{
public void run()
{

while(!interrupted())
{
for(int i=0;i<=10000;i++)
;

try
{
sleep(5);
}
catch(InterruptedException e)
{
System.out.println("catch it");
break;
}
}
System.out.println("interrupt()");
}

public static void main(String[] args) throws Exception
{
Gm g=new Gm();
Thread t=new Thread(g);
g.start();
Thread.sleep(1000);
System.out.println(
"the main thread want to interrupt the sub thread");
g.interrupt();

}
}

//不懂得地方再发短消息给我
skymotor 2003-04-10
  • 打赏
  • 举报
回复
join()用于调用线程等待本线程结束。应对另一线程调用这个方法,而不是对执行代码的线程。stop()在JAVA2中已经过时,详细原因见http://java.sun.com/docs/books/tutorial/post1.0/preview/threads.html
interrupt()是用来中断线程的,好象不是用来结束线程的。
mercury1231 2003-04-10
  • 打赏
  • 举报
回复
yes
徐蕴 2003-04-10
  • 打赏
  • 举报
回复
interrupt()

62,614

社区成员

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

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