我正在使用java8&我编写了一个程序来识别java中Threads的'Synchronized()'的行为。这些是我创建的类和&我得到了意想不到的输出。
public class PrintNumberDemo {
public void printNumbers() {
for(int i=0;i<=20;i++) {
System.out.println(i);
}
}
}
public class PrintStarDemo {
public void printStars() {
for(int i=0;i<=20;i++) {
System.out.println("*");
}
}
}
public class PrintThread implements Runnable {
Thread t;
String name;
PrintNumberDemo pd;
PrintStarDemo ps;
PrintThread(Object ob, String name) {
if (ob instanceof PrintNumberDemo) {
this.pd = (PrintNumberDemo) ob;
}
if (ob instanceof PrintStarDemo) {
this.ps = (PrintStarDemo) ob;
}
this.name = name;
}
@Override
public void run() {
// TODO Auto-generated method stub
if (pd != null)
synchronized (pd) {
pd.printNumbers();
}
if (ps != null)
synchronized (ps) {
ps.printStars();
}
}
public void start() {
if (t == null) {
t = new Thread(this, name);
System.out.println("Starting " + name);
t.start();
}
}
}
public class TestPrintDemo {
public static void main(String[] args) {
PrintNumberDemo pd1= new PrintNumberDemo();
PrintStarDemo ps1 = new PrintStarDemo();
PrintThread t1 = new PrintThread(pd1,"Thread-01");
PrintThread t2 = new PrintThread(ps1,"Thread-02");
t1.start();
t2.start();
}
}
输出:
Starting Thread-01 Starting Thread-02 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
* 17 18 19 20
任何人都可以解释,为什么它会显示出这样的输出?