A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 梁志斌 中级黑马   /  2016-1-21 18:46  /  509 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

class MyThread extends Thread{
private String data;
public void run(){
synchronized(data){
for(int i = 0; i<10; i++){
try{
Thread.sleep((int)(Math.random()*1000) );
}catch(Exception e){}
System.out.println(data);
}
}
}
}
public class TestMyThread {
public static void main(String args[]){
Thread t1 = new MyThread();
Thread t2 = new MyThread();
t1.setName(“hello”);
t2.setName(“world”);
t1.start();
t2.start();
}
}
这题运行报错的原因是啥?

1 个回复

倒序浏览
你的锁对象不是唯一的,达不到同步效果!你的所对象是没有任何赋值,是空参,引用这样的所对象会报NullPointerException (引用异常)!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马