相关疑难解决方法(0)

Java中的"实现Runnable"与"扩展线程"

从我在Java中使用线程的时间开始,我发现了这两种编写线程的方法:

implements Runnable:

public class MyRunnable implements Runnable {
    public void run() {
        //Code
    }
}
//Started with a "new Thread(new MyRunnable()).start()" call
Run Code Online (Sandbox Code Playgroud)

或者,用extends Thread:

public class MyThread extends Thread {
    public MyThread() {
        super("MyThread");
    }
    public void run() {
        //Code
    }
}
//Started with a "new MyThread().start()" call
Run Code Online (Sandbox Code Playgroud)

这两个代码块有什么显着差异吗?

java multithreading runnable implements java-threads

2023
推荐指数
30
解决办法
67万
查看次数

Java join()方法

我有一个看起来很奇怪的例子.

public class Join {
    public static void main(String[] args) {
        Thread t1 = new Thread(
                new Runnable() {
                    public void run() {
                        System.out.println(Thread.currentThread().getName());
                    }
                }
        );
        Thread t2 = new Thread(t1);
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        try {t1.join();} catch (InterruptedException ie) {}
        t2.start();
    }
}
Run Code Online (Sandbox Code Playgroud)

我们只看到打印t1.如果我们将评论"t1.join",我们将得到预期的输出(t1 t2).为什么?

java multithreading

4
推荐指数
1
解决办法
695
查看次数

使用Runnable和Thread创建线程的区别?

这段代码工作正常但如果我在第6行使用构造函数Thread(name)而不是Thread(this,name)它不起作用我只是想知道是什么产生了区别?

public class threadtest implements Runnable{
    Thread t;

    public threadtest(String name)
    {
        System.out.println("satheesh");
        Thread t=new Thread(this,name);
        t.start();
        t=null;
        //System.out.println(this+"\n"+t);
    }

    public void run(){
        System.out.println("satheesh");
        for(int i=0;i<=10;i++)
        {
            try{
                System.out.println("satheesh");
                Thread.sleep(1000);
                System.out.print(Thread.currentThread());
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }
    }

    public static void main(String args[])
    {
        threadtest ob=new threadtest("satheesh");       
    }
}
Run Code Online (Sandbox Code Playgroud)

java

1
推荐指数
1
解决办法
2349
查看次数