packagecom.maven.testproject2.testweb2;publicclassApp{publicstaticvoidmain(String[]args){System.out.println("HelloWorld!");Testt1=newTest("1",1);t1.start();Testt2=newTest...
package com.maven.testproject2.testweb2;
public class App {
public static void main(String[] args) {
System.out.println("Hello World!");
Test t1 = new Test("1", 1);
t1.start();
Test t2 = new Test("2", 2);
t2.start();
Test t3 = new Test("3", 3);
t3.start();
}
}
class Test extends Thread {
private static String lock = "0";
private int age;
public Test(String lock, int age) {
Test.lock = lock;
this.age = age;
}
public void printAge() {
synchronized (lock) {
while (true) {
System.out.println(Thread.currentThread().getName() + ":age="
+ age + ",lock=" + lock);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void run() {
System.out.println(Thread.currentThread().getName() + ":in");
printAge();
}
}
为什么会有时候出现这样的运行结果呢,已经while(true)了,一旦一个线程占有了后又不会释放lock,为啥能出现两个线程交替执行的现象呢,结果如下。。。
Hello World!
Thread-0:age=1,lock=3
Thread-2:age=3,lock=3
Thread-2:age=3,lock=3
Thread-0:age=1,lock=3
Thread-0:age=1,lock=3
Thread-2:age=3,lock=3
Thread-0:age=1,lock=3
Thread-2:age=3,lock=3
Thread-0:age=1,lock=3
Thread-2:age=3,lock=3
感激不尽~~~
展开