会使用同一个Static INt的,但在你的程序中无法体现出来

解决方案 »

  1.   

    关键是这句System.out.println(s + ":x=" + x++ + "y=" + y++); 
    两个线程打印出来的结果会是怎样?
      

  2.   

    结果没什么问题啊
    线程1和线程2的i是不同的两个
    你在run里先i++就明白了
      

  3.   

    什么不一样。
    你把while里面的代码换成
    x++;
    y++;
    if(x!=y) {
      System.out.println(s + ":x=" + x + " y=" + y); 
    }
    不要加sleep
      

  4.   

    应该
    new Thread(new MyThread()).start(); 
    new Thread(new MyThread()).start();
    要不用的调用的是同一对象的方法
      

  5.   

    >
    new Thread(new MyThread()).start(); 
    new Thread(new MyThread()).start();
    <
    这样一样有问题,
    String s = "Thread" + i++; 中i++又不是一个原子操作,
    即使是对java基本类型中除了double,long之外的类型的变量做读取或赋值这样的原子操作,也必须要声明相应的变量为volatile
      

  6.   

    static i和int x,y?楼主是这个意思?
      

  7.   

    上面的问题会出现线程同步
    可以使用join或synchronized 避免数据被破坏.
    join方法
    public class a
    {
    public static void main(String args[])
    {
    MyThread mt=new MyThread();
    Thread t1=new Thread(mt);
    Thread t2=new Thread(mt);
    t1.start();
    try
    {
    t1.join();
    }
    catch(InterruptedException e1){}
                t2.start();
    try
    {
    t2.join();
    }
    catch(InterruptedException e2){}
    }
    }
    class MyThread implements Runnable
    {
    int x,y;
    static int i=1;
    public void run()
    {
    String s="Thread"+i++;
    for(int m=0;m<10;m++)
    {
    System.out.println(s+":x="+x+++"y="+y++);
    try
    {
    Thread.currentThread().sleep(10);

    }
    catch(InterruptedException ie)
    {
    }
    }
    }
    }
    synchronized方法:
    public class a
    {
    public static void main(String args[])
    {
    MyThread mt=new MyThread();

    new Thread(mt).start(); new Thread(mt).start();
    }
    }
    class MyThread implements Runnable
    {
    static int x,y;
        static int i=1; public synchronized static void wt()
    { String s="Thread"+i++;
    for(int m=0;m<10;m++)
    {
    System.out.println(s+":x="+ x++ +"y="+ y++);
    try
    {
    Thread.currentThread().sleep(10);

    }
    catch(InterruptedException ie)
    {
    }
    }
    }
    public void run()
    {
    wt();
    }
    }