1
当这里的synchronized块不工作原理:无法在Thread类扩展到同步两个线程,但实现Runnable接口
class NewThreadt extends Thread {
synchronized void dota(){
for(int i = 5; i > 0; i--)
{
System.out.println(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
}
}
// This is the entry point for the second thread.
public void run() {
dota() ;
System.out.println("Exiting child thread.");
System.out.println(Thread.currentThread()); //gives the name of thread
}
}
class trial {
public static void main(String args[]) {
NewThreadt t=new NewThreadt();
NewThreadt q=new NewThreadt();
t.start();
q.start(); both are in main
System.out.println("Main thread exiting.");
}
}
输出:
Main thread exiting.
5
5
4
4
3
3
2
2
1
1
但是,当我做如下修改同步块的工作原理:
class NewThreadt implements Runnable //instead of class NewThreadt extends Thread
NewThreadt abc=new NewThreadt(); //Changes in main()
Thread t=new Thread(abc);
Thread q=new Thread(abc);
t.start();
q.start();
输出:
Main thread exiting.
5
4
3
2
1
5
4
3
2
1
这是怎么发生的?这两个例子都不一样吗?