java中的同步方法实现和错误行为

时间:2014-02-17 07:12:40

标签: java multithreading synchronized

class prab implements Runnable {
    public synchronized void toTest() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(2 * 1000);
            } catch (Exception e) {
                System.out.println("Exception" + e);
            }
            System.out.println("I am from Prab " + i
                    + Thread.currentThread().getName());
        }
    }

    @Override
    public void run() {
        toTest();
    }

}

public class threadClass {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("---");
        Thread t = new Thread(new prab());
        Thread c = new Thread(new prab());
        t.start();
        t.setName("I am T");
        c.start();
        c.setName("I am c");
        System.out.println("From Main thread");
    }
}

Out Put:---

From Main thread
I am from Prab 0I am T
I am from Prab 0I am c
I am from Prab 1I am c
I am from Prab 1I am T
I am from Prab 2I am c
I am from Prab 2I am T
I am from Prab 3I am T
I am from Prab 3I am c
I am from Prab 4I am T
I am from Prab 4I am c
I am from Prab 5I am T
I am from Prab 5I am c
I am from Prab 6I am T
I am from Prab 6I am c
I am from Prab 7I am T
I am from Prab 7I am c
I am from Prab 8I am c
I am from Prab 8I am T
I am from Prab 9I am T
I am from Prab 9I am c

预期的O / P:第一个线程T应该完成然后线程c。

3 个答案:

答案 0 :(得分:3)

您对不同的对象有synchronized,因为在方法签名上添加synchronized会锁定当前实例。你创造了两个对象。

同步应该在公共对象上,然后只有你可以看到预期的输出。对两个线程使用一个prab对象,然后查看输出

prab p = new prab();
Thread t = new Thread(p);
Thread c = new Thread(p);

答案 1 :(得分:0)

synchronized将阻止常见对象或方法。尝试使用静态共享或只创建一个prab对象

答案 2 :(得分:0)

synchronize在对象实例上同步,而不是类型。