站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题请教一个JAVA多线程的代码,我不太明白,感谢。。

请教一个JAVA多线程的代码,我不太明白,感谢。。

摘要: 请教一个JAVA多线程的代码,我不太明白,感谢。。


public class test
{
public static void main(String[] args)
{
ThreadTest t=new ThreadTest();
Thread pp=new Thread(t);
pp.start();
int i=0;
while(true)
{
if(i==100)
{
try
{
pp.join();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
System.out.println("main Thread "+i++);
}
}
}
class ThreadTest implements Runnable
{
public void run()
{
String str=new String();
int i=0;
while(true)
{
System.out.println(Thread.currentThread().getName()+" "+i++);
}
}
}



这段代码是什么意思,join有什么作用,感谢。。。。为什么没有打印System.out.println("main Thread "+i++);。。。。。

感谢。。请教了


JOIN的作用就是等待现成结束
System.out.println("main Thread "+i++);
改成
i++;
System.out.println("main Thread "+i);


join是停止线程的作用。threadtest里的这段代码是重写run()这个函数。因为当你声明一个线程实例时,调用start()的方法,该方法会调用run()方法。你可以使用默认的run()方法,也可以自己该写它。
ThreadTest t=new ThreadTest();
Thread pp=new Thread(t);
pp.start();
这句话就是声明了一格线程实例 ,pp.start()这句调用了threattest的run() 方法!

好了 给分吧!!!
点"管理",给分


感谢楼上,还是没有打印那句话,您调试看看,帮帮忙


class test
{
public static void main(String[] args)
{
ThreadTest t=new ThreadTest();
Thread pp=new Thread(t);
pp.start();
int i=0;
while(true)
{
if(i==100)
{
try
{
pp.join();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
System.out.println("main Thread "+i++);
try
{
Thread.currentThread().sleep(500);
}
catch(Exception e){}
}
}
}
class ThreadTest implements Runnable
{
public void run()
{
String str=new String();
int i=0;
while(i<200)
{
try
{
Thread.currentThread().sleep(500);
}
catch(Exception e){}
System.out.println(Thread.currentThread().getName()+" "+i++);


}
}
}


用join()是不对的,达不到你说的那种效果。改成pp.sleep(1000);或其它数值就可以了



public class TestThread {

public static void main(String[] args)
{
ThreadTest t=new ThreadTest();
Thread pp=new Thread(t);
pp.start();
int i=0;
while(true)
{
if(i==100)
{
try
{
pp.sleep(1000);
//pp.join();用这个达不到你说的那种效果 。
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}

System.out.println("main Thread "+i++);
}
}
}
class ThreadTest implements Runnable
{
public void run()
{
String str=new String();
int i=0;
while(true)
{
System.out.println(Thread.currentThread().getName()+" "+i++);
}
}
}




pp.join();是等线程pp结束才执行这个语句下边的代码

但pp里while(true)且没有结束条件:就是一个死循环,有啥好说的
永远不会结束


System.out.println("main Thread "+i++);
永远不会被执行到!



while(true)->while(i<1000)
就会有下面的打印了


也可以用pp.join(1000);定义一个最长等待时间.

public final void join(long millis)
等待该线程终止的时间最长为 millis 毫秒。超时为 0 意味着要一直等下去。


↑返回目录
前一篇: 请教,为什么线程非安全的还是正确的结果
后一篇: 20分~求Think in java 第3版习题答案~!