关于Thread的执行代码块疑问
今天看张效祥的java培训教程关于Thread有点不明白
代码如下:
class TestThread implements Runnable
{
int tickets = 100;
String str = new String( " ");
public void run()
{
if (str.equals( "method "))
{
while(true)
{
sale();
}
}
else
{
while(true)
{
synchronized(str)
{
if (tickets > 0)
{
System.out.println(Thread.currentThread().getName() + "while : " + tickets--);
try{Thread.sleep(1);}catch(Exception e){}
}
}
}
}
}
public synchronized void sale()
{
if (tickets > 0)
{
System.out.println(Thread.currentThread().getName() + "sale : " + tickets--);
try{Thread.sleep(1);}catch(Exception e){}
}
}
}
public class test
{
public static void main(String [] args)
{
TestThread tt = new TestThread();
new Thread(tt).start();
try{Thread.sleep(1);}catch(Exception e){}
tt.str = new String( "method ");
new Thread(tt).start();
}
}
执行的结果真的是线程0和线程1在交替执行
if (str.equals( "method "))的if部分和else部分
Thread-0while :100
Thread-0while :99
Thread-1sale : 98
Thread-0while :97
Thread-0while :96
.......
Thread-0while :4
Thread-1sale : 3
Thread-0while :2
Thread-1sale : 1
看看main函数是生成了thread1后就把str设成了method的
我觉得在str被设成了method之后,不管是thread0还是thread1都应该只执行sale函数呀,因为那个时候str一直都是method呀
线程的工作原理是什么呀,是不是通过用start让每个线程反复的执行run函数
可是这个例子中两个线程在反复的执行run函数的一部分
为什么线程0会纪录他第一次执行时str的值呢
因为只要线程1执行了就证明str已经变成了method
但在线程1执行后线程0执行的时候还是会执行sale以外的代码块
谢谢
请高手指导
万分感谢
[解决办法]
线程的工作原理是一次调用start方法,然后系统自动调用run方法,只调用一次。