【发布时间】:2013-11-24 19:04:33
【问题描述】:
我想了解下面java中的线程同步是代码有一个名为Interview的主类。在那个类中,我正在创建两个对象
public class Interview{
/**
* @param args the command line arguments
* @throws java.lang.InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO code application logic here\
Race r1=new Race();
r1.setA(15);
Thread t1=new Thread(r1, "First thread");
Race r2=new Race();
r2.setA(25);
Thread t2=new Thread(r2, "Second thread");
t1.start();
t2.start();
}
}
还有其他类具有名为 Race 的 run 方法,这里是代码
public class Race implements Runnable{
int a;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
@Override
public void run() {
try {
print();
} catch (InterruptedException ex) {
Logger.getLogger(Race.class.getName()).log(Level.SEVERE, null, ex);
}
}
public synchronized void print() throws InterruptedException{
for(int i=1;i<=10;i++){
System.out.println(a*i);
Thread.sleep(1000);
}
}
}
对于每个对象,我给出不同的 a 值,然后尝试同步打印方法,但它不起作用。我使用的概念是两个试图同时访问分片资源的线程不能通过使用同步方法来做到这一点。因此,在我的情况下,两个线程 t1 和 t2 试图同时访问 print 方法,所以我将 synchronized 关键字与 print 方法一起使用,但结果仍然相同。我想要的是线程 t1 首先执行,即15 30 45 60..... 然后螺纹 t2 即 25 50 75... 等等。 如果我的概念不清楚,请纠正我..
【问题讨论】:
-
方法不是共享资源!共享资源只能是类对象的字段。在您的示例中,没有共享资源,因为两个 Race 实例都有自己的字段 a。
标签: java multithreading synchronization synchronized