当我使用“同步”时,为什么我的帖子不会一个接一个地执行?

时间:2016-09-18 10:50:41

标签: java multithreading synchronization

我使用synchronized来执行第一个线程,然后在第一个线程完成时执行另一个线程,但是两个线程同时执行。为什么呢?

public class PrintNums extends Thread {
    int num;

    public PrintNums(int x) {
        this.num = x;  
    }

    @Override
    public void run() {
        this.count();
    }

    public synchronized void count() {
        for (int i = 1; i <= 5; i++) {
            System.out.println((2 * i - this.num));
            try {
                Thread.currentThread().sleep(1000);
            } catch (InterruptedException ex) {
            }
        }
    }

    public static void main(String[] args) {
        PrintNums odd = new PrintNums(1);
        PrintNums even = new PrintNums(0);

        odd.start();
        even.start();
    }
}

1 个答案:

答案 0 :(得分:2)

没有明确目标的

public <T> Class<T> myMethod(Class<T> theClass, T obj) // other stuffs return theClass; } 意味着synchronized:每个线程都在自身同步,因此没有冲突。如果要序列化它们,可以使用synchronized(this)

请注意,通常使用比使用显式线程更好的构造,例如执行程序或锁存器。

相关问题