先看下面一个程序,很简单。
class fun{
static Thread la,ha;
public static void main(String[] args){
la = new Thread(){
public void run(){
System.out.println ("A");
try{
//ha.sleep(5000);
}catch(Exception e){
System.out.println ("B");
}
System.out.println ("C");
}
};
ha = new Thread(){
public void run(){
System.out.println ("D");
try{
synchronized(ha)
{
ha.wait(5000);
}
}catch(Exception e){
System.out.println ("E");
}
System.out.println ("F");
}
};
ha.start();
la.start();
}
}然而程序稍微变一下,结果就不一样了class fun{
static Thread la,ha;
public static void main(String[] args){
la = new Thread(){
public void run(){
System.out.println ("A");
try{
//ha.sleep(5000);
}catch(Exception e){
System.out.println ("B");
}
System.out.println ("C");
}
};
ha = new Thread(){
public void run(){
System.out.println ("D");
try{
synchronized(la)
{
la.wait(5000);
}
}catch(Exception e){
System.out.println ("E");
}
System.out.println ("F");
}
};
ha.start();
la.start();
}
}等待的5秒到哪里去了?
还有就是synchronized(la)和synchronized(this)有什么区别啊?
x.wait();
x是线程还是对象?还是2个都可以。这句话的具体含义是什么?是让当前线程等待,激活x?还是让x线程等待?
还有关于x.notify()也有同样的困惑,高手帮帮忙,谢谢。
都说wait()不放在同步块中回抛出异常,但我好象也见过wait()不在同步块中也能正常运行的,好奇怪?
class fun{
static Thread la,ha;
public static void main(String[] args){
la = new Thread(){
public void run(){
System.out.println ("A");
try{
//ha.sleep(5000);
}catch(Exception e){
System.out.println ("B");
}
System.out.println ("C");
}
};
ha = new Thread(){
public void run(){
System.out.println ("D");
try{
synchronized(ha)
{
ha.wait(5000);
}
}catch(Exception e){
System.out.println ("E");
}
System.out.println ("F");
}
};
ha.start();
la.start();
}
}然而程序稍微变一下,结果就不一样了class fun{
static Thread la,ha;
public static void main(String[] args){
la = new Thread(){
public void run(){
System.out.println ("A");
try{
//ha.sleep(5000);
}catch(Exception e){
System.out.println ("B");
}
System.out.println ("C");
}
};
ha = new Thread(){
public void run(){
System.out.println ("D");
try{
synchronized(la)
{
la.wait(5000);
}
}catch(Exception e){
System.out.println ("E");
}
System.out.println ("F");
}
};
ha.start();
la.start();
}
}等待的5秒到哪里去了?
还有就是synchronized(la)和synchronized(this)有什么区别啊?
x.wait();
x是线程还是对象?还是2个都可以。这句话的具体含义是什么?是让当前线程等待,激活x?还是让x线程等待?
还有关于x.notify()也有同样的困惑,高手帮帮忙,谢谢。
都说wait()不放在同步块中回抛出异常,但我好象也见过wait()不在同步块中也能正常运行的,好奇怪?
synchronized(this)是先引用this所引用的Stack对象的锁
------------
x是线程
synchronized(this)是先引用this所引用的Stack对象的锁
x.wait(); //x 是线程.
x.notify(); // x唤醒第一个处于等待x对象锁的线程结束等待.