【发布时间】:2016-05-12 08:22:30
【问题描述】:
这些只是询问我问题的示例代码,其他语句被省略 这里 NewClass 的实例同时传递给 Foot 和 Hand 对象 因此所有实例 NewClass、foot 和 hand 共享 NewClass 的变量 sno。
public class NewClass {
volatile int sno = 100;
public static void main(String args[])
{
NewClass n = new NewClass();
Foot f = new Foot(n);
Hand h = new Hand(n);
f.start();
h.start();
}
}
public class Foot implements Runnable{
Thread t;
NewClass n;
public Foot(NewClass n)
{
this.n = n;
}
public void run(){
for(int i=0;i<100;i++)
{
System.out.println("foot thread "+ i+" "+n.sno);
n.sno=(-1)*n.sno;
Thread.sleep(1); // surrounded by try-catch
}
}
}
public class Hand implements Runnable {
Thread t;
NewClass n;
public Hand(NewClass n)
{
this.n = n;
}
public void run(){
for(int i=0;i<100;i++)
{
System.out.println("hand thread "+ i+" "+n.sno);
n.sno=(-1)*n.sno;
Thread.sleep(1); // surrounded by try -catch
}
}
}
这里 seq.no 的符号每次都在变化,但是当被其他线程使用时,变化很多次都没有反映出来,好像更新需要时间。所以请帮忙,
【问题讨论】:
-
在您的代码中,您不要在 Runnable 中使用线程。通常不会将要运行 Runnable 的线程放在 Runnable 中。见stackoverflow.com/questions/541487/…
标签: java multithreading volatile