package ThreadTest;
public class MockTest {
public static void main(String[] args) {
Test t1 = new Test() ;
t1.run() ;
for(int k=0;k<5;k++){
t1.addA() ;
System.out.println(" Main Thread Add a: " +t1.a);
}
}
}
class Test implements Runnable{
public int a = 0 ;
public void run() {
synchronized (this) {
while(a<4){
System.out.println("a<4 " + Thread.currentThread().getName()+"--a..." +a);
try {
// Thread.sleep(1000);
this.wait(1000) ;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(" a>4...." + Thread.currentThread().getName());
}
public synchronized void addA(){
a++ ;
}
}
------解决思路----------------------
仔细看看代码吧,主函数中线程调用都写错了,何来释放锁一说
------解决思路----------------------
package ThreadTest;
public class MockTest {
public static void main(String[] args) {
Test t1 = new Test() ;
new Thread(t1).start();
//t1.run() ;
for(int k=0;k<5;k++){
t1.addA() ;
System.out.println(" Main Thread Add a: " +t1.a);
}
}
}
------解决思路----------------------
t1在主线程跑的,没在新线程运行。楼上正解。
------解决思路----------------------
t1.run() ;这不是开启线程的方法,仅仅是在主线程里面运行一个方法而已,也就是说现在就一个主线程。然后run里面有这样一句this.wait(1000) ;让主线程等待,那么谁来唤醒主线程呢
------解决思路----------------------
启动线程用start方法,调用run方法就和调用普通方法一样,你一直在while循环中,没有调用到addA方法,当然一直是这样的结果