public class TestThread implements Runnable{
int b = 0;
public synchronized void f1(){
b =3000;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("b:"+b);
}
public synchronized void f2(){
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
e.printStackTrace();
}
b = 2000;
}
public void run(){
f1();
}
public static void main(String[] args){
TestThread tt = new TestThread();
Thread t = new Thread(tt);
t.start();
tt.f2();
System.out.println(tt.b);
}}
////
这个关于锁的问题是来源与马士兵的视频~~~按照他给我的理解是都有锁时,主线程的先进行,然后子线程。
但不理解的是t.start()优先于System.out.println(tt.b);
结果是 1000;
b:1000;但是我修改了子线程的休眠时间比如改为15000时,数据就变了啊
结果是 2000
b:1000;
int b = 0;
public synchronized void f1(){
b =3000;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("b:"+b);
}
public synchronized void f2(){
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
e.printStackTrace();
}
b = 2000;
}
public void run(){
f1();
}
public static void main(String[] args){
TestThread tt = new TestThread();
Thread t = new Thread(tt);
t.start();
tt.f2();
System.out.println(tt.b);
}}
////
这个关于锁的问题是来源与马士兵的视频~~~按照他给我的理解是都有锁时,主线程的先进行,然后子线程。
但不理解的是t.start()优先于System.out.println(tt.b);
结果是 1000;
b:1000;但是我修改了子线程的休眠时间比如改为15000时,数据就变了啊
结果是 2000
b:1000;
public class TestThread implements Runnable { int b = 0;
public synchronized void f1() {
System.out.println("f1() 获得锁 --> b: " + b);
b = 3000;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f1() 释放锁 --> b: " + b);
} public synchronized void f2() {
System.out.println("f2() 获得锁 --> b: " + b);
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
e.printStackTrace();
}
b=2000;
System.out.println("f2() 释放锁 --> b: " + b);
} public void run() {
f1();
} public static void main(String[] args) {
TestThread testThread = new TestThread();
Thread t = new Thread(testThread);
t.start();
testThread.f2();
System.out.println("main() --> b: " + testThread.b);
}
}
好好体会吧。。
先输出了System,是因为主线程(main)抢到了CPU, 你在System.out... 前加一句 Thread.sleep(1) 睡1毫秒, 子线程就先抢到了CPU,线程具有不定性,抢占CPU具有不确定性,, 还是建议看看线程的几个状态是怎么转换