hganbo
发贴: 2
积分: 0
|
于 2004-12-15 17:21
小弟最近在做一个项目遇到一点线程同步的问题,还没有找出具体的问题。 怀疑问题出在多线程访问静态方法上,但没有找到有相关资料讲这方面的问题,所以只好请教一下各位java高手了。
我的原来程序是这样设计的,对于一些常用的方法,都用静态方法来实现,在多线程程序中直接调用,静态方法由于没有使用静态变量,所以没有进行线程同步。
类似以下程序:
class ThreadI { public static void main(String[] arg) {
TestI p = new TestI("thread 1"); new TestI("thread 2").start(); new TestI("thread 3").start(); new TestI("thread 4").start(); new TestI("thread 5").start(); new TestI("thread 6").start(); new TestI("thread 7").start(); new TestI("thread 8").start(); new TestI("thread 9").start(); new TestI("thread 10").start(); new TestI("thread 11").start(); new TestI("thread 12").start(); new TestI("thread 13").start(); new TestI("thread 14").start(); new TestI("thread 15").start(); new TestI("thread 16").start(); new TestI("thread 17").start(); new TestI("thread 18").start(); new TestI("thread 19").start(); new TestI("thread 20").start(); p.start(); } }
class TestI extends Thread { String s ; TestI(String sTemp){ this.s = sTemp; } public void run() { try{
Thread.currentThread().sleep( 1000*5); }catch(Exception ex){}
for(int i=0;i<100;i++){ System.out.println(T.t( this.s + " "+ i)); } } }
class T{ public static String t(String sTemp){ String aa = sTemp; return aa; } }
从上面的例子程序打出的结果,我看不出有线程访问冲突的地方。
我的疑问是:对于T.t这种静态方法,在不同线程调用时,jvm究竟是怎么进行处理的? 我自己的理解是对于这样的静态方法是先实例化成各线程堆栈内的具体方法,然后再进行运算,由于都是局部变量,没有使用静态变量,各线程之间是不存在资源冲突的。但没有找到资料来证实这样的理解,所以比较烦恼。还请各位帮忙解决一下。
|