初學多線程求教,調用synchronized(Class.forName(""))時拋出異常

东门吹雪 2011-08-26 03:03:51

public class J_BlockClass extends Thread
{
public static int m_data=0;
public static int m_times=1000;
public int m_ID;
public boolean m_done;

J_BlockClass(int id)
{
m_ID = id;
}

public void run()
{
m_done = false;
int d = ((m_ID%2==0) ? 1:-1);
System.out.println("Run Thread: " +m_ID+ "(Increment is: " + d + ")");

try
{
synchronized(Class.forName("J_BlockClass"))
{
System.out.println("Thread: " + m_ID + "Enter into synchronized block, m_data= " + m_data);
for (int i=0; i<m_times; i++)
for(int j=0; j<m_times; j++)
m_data += d;
System.out.println("Thread: " +m_ID + "Leave synchronized block, m_data= " + m_data);
}
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
System.err.println(e);
}

m_done = true;
System.out.println("End Thread: " + m_ID);
}

public static void main(String args[])
{
J_BlockClass t1 = new J_BlockClass(1);
J_BlockClass t2 = new J_BlockClass(2);
t1.m_done = false;
t2.m_done = false;
t1.start();
t2.start();

while (!t1.m_done || !t2.m_done)
;
System.out.println("The result is: m_data = " + m_data);
}
}


拋出異常:
java.lang.ClassNotFoundException: J_BlockClass
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301

。。。。。。。。。。。。
...全文
94 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
东门吹雪 2011-08-26
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 shuwei003 的回复:]
是不是你用了包了,如果用了包应该写Class.forName("包名.J_BlockClass")
[/Quote]

哈哈,果然啊, you are so smart ,ths,看來我還得加油啊
shuwei003 2011-08-26
  • 打赏
  • 举报
回复 1
这个我这里运行没报错,输出:
Run Thread: 1(Increment is: -1)
Thread: 1Enter into synchronized block, m_data= 0
Run Thread: 2(Increment is: 1)
Thread: 1Leave synchronized block, m_data= -1000000
End Thread: 1
Thread: 2Enter into synchronized block, m_data= -1000000
Thread: 2Leave synchronized block, m_data= 0
End Thread: 2
The result is: m_data = 0

是不是你用了包了,如果用了包应该写Class.forName("包名.J_BlockClass")

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧