从我在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)
这两个代码块有什么显着差异吗?
当我学习如何使用wait和notify时,我得到一个奇怪的东西,下面两部分代码是相似的,但是它们的结果是如此不同,为什么呢?
class ThreadT implements Runnable{
public void run()
{
synchronized (this) {
System.out.println("thead:"+Thread.currentThread().getName()+" is over!");
}
}
}
public class TestWait1 {
public static void main(String[] args) {
Thread A = new Thread(new ThreadT(),"A");
A.start();
synchronized (A) {
try {
A.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" is over");
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
thead:A结束了!
主要结束了
class ThreadD implements Runnable{
Object o ;
public ThreadD(Object o)
{
this.o = o;
}
public void run() …Run Code Online (Sandbox Code Playgroud)