1

不确定我是否做对了。我需要创建一个新线程来写出一定次数的消息。我认为这到目前为止有效,但不确定它是否是最好的方法。然后我需要在线程完成运行后显示另一条消息。我怎么做 ?使用 isAlive() 吗?我该如何实施?

public class MyThread extends Thread {

    public void run() {
        int i = 0;
        while (i < 10) {
            System.out.println("hi");
            i++;
        }
    }

    public static void main(String[] args) {
        String n = Thread.currentThread().getName();
        System.out.println(n);
        Thread t = new MyThread();
        t.start();
    }
}
4

3 回答 3

5

到现在为止,你都走上了正轨。现在,要显示另一条消息,当该线程完成时,您可以从主线程调用Thread#join该线程。InterruptedException当您使用t.join方法时,您还需要处理,

然后,当您的线程t完成时,您的主线程将继续。所以,像这样继续你的主线程: -

t.start();
try {
    t.join();
} catch (InterruptedException e) {
    e.printStackTrace();
}
System.out.println("Your Message"); 

当您t.join在特定线程(此处为主线程)中调用时,该线程将继续其进一步执行,仅当线程t完成执行时。

于 2012-11-08T16:37:45.493 回答
1

扩展Thread类本身通常不是一个好习惯。

您应该Runnable按如下方式创建接口的实现:

public class MyRunnable implements Runnable {

    public void run() {
        //your code here
    }
}

并将它的实例传递给线程,如下所示:

MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();

请在此处查看此答案:Implementing Runnable vs. extended Thread

于 2012-11-08T16:46:35.770 回答
0

这就是你可以做到的......

class A implements Runnable
{
    public void run()
    {
    for(int i=1;i<=10;i++)
    System.out.println(Thread.currentThread().getName()+"\t"+i+"  hi");
    }
}
class join1
{
public static void main(String args[])throws Exception
    {
    A a=new A();
    Thread t1=new Thread(a,"abhi");
    t1.start();
    t1.join();
    System.out.println("hello this is me");//the message u want to display
    }
}

查看 join() 加入的详细 信息

于 2012-11-08T16:55:31.430 回答