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");
}
}
输出:---
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。
最佳答案
您已在不同对象上进行了同步,因为在方法签名上添加同步将锁定当前实例。您已经创建了两个对象。
同步应该在公共(public)对象上,然后只有您才能看到预期的输出。对两个线程使用一个 prab
对象,然后查看输出
prab p = new prab();
Thread t = new Thread(p);
Thread c = new Thread(p);
关于java - java中同步方法的实现和错误行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21822852/