日期:2014-05-20  浏览次数:20622 次

我想验证一下线程不同步时,成员变量会一致时
public class TestTongbu{
    public static int i=0;
    public static void main(String [] args){
    //这里错了?提示:无法从静态上下文中引用非静态变量  this?
    mythread t1=new mythread("t1");
mythread t2=new mythread("t2");
t1.start();
t2.start();
    }
    class mythread extends Thread {
        mythread(String s){
    super(s);
    }
        public void run(){
    i++;
try{
Thread.sleep(1);
}catch(InterruptedException e){
    return;
}        
    System.out.println(Thread.currentThread().getName()+i);
    }
    }
}



----------- //这里错了?提示:无法从静态上下文中引用非静态变量  this?
    mythread t1=new mythread("t1");
mythread t2=new mythread("t2");
------ 我该怎么修改才能通过编译程序,看到不同步的效果呀

------解决方案--------------------
方法1、加static
static class mythread extends Thread

方法2、将mythread类定义移动到TestTongbu类外部
public class TestTongbu{
//...
}
class mythread extends Thread{

}


------解决方案--------------------
package com.demo;

public class TestTongbu {
public static int i = 0;

public static void main(String[] args) {
// static修饰的方法或代码块中不能引用具体的对象,this指当前对象,所以不能使用this
TestTongbu testTongbu = new TestTongbu();
MyThread t1 = testTongbu.new MyThread("t1");
MyThread t2 = testTongbu.new MyThread("t2");
t1.start();
t2.start();
}

class MyThread extends Thread {
MyThread(String s) {
super(s);
}

public void run() {
while(true) {
try {
i++;
Thread.sleep(1);
System.out.println(Thread.currentThread().getName()+i);
} catch (InterruptedException e) {
return;
}

}
}
}
}


你的代码实在是太烂了,类名要大写!内部类的new的方法是,使用外部类对象.new这样来new一个对象,你完全都不懂得。你得去看下内部类的相关知识。

然后,或者也可以使用static的内部类,就不用像我代码中那样,使用外部类去new了。

不知道你懂了没,欢迎继续提问。
------解决方案--------------------
引用:
方法1、加static
static class mythread extends Thread

方法2、将mythread类定义移动到TestTongbu类外部
public class TestTongbu{
//...
}
class mythread extends Thread{

}

他想要线程间共享变量,你的方法2对于他不合适。
------解决方案--------------------
你想验证,最好在 i++ 加上个循环,比如100次。这样能明显看出异常。
然后还要在两个start之后加上
t1.join();
t2.join();

等线程执行完。
最后在print i。

------解决方案--------------------
引用:
Quote: 引用:

方法1、加static
static class mythread extends Thread

方法2、将mythread类定义移动到TestTongbu类外部
public class TestTongbu{
//...
}
class mythread extends Thread{

}

他想要线程间共享变量,你的方法2对于他不合适。



可以的,i换成TestTongbu.i啊。
------解决方案--------------------
引用:
Quote: 引用:

Quote: 引用:

方法1、加static
static class mythread extends Thread

方法2、将mythread类定义移动到TestTongbu类外部
public class TestTongbu{
//...
}
class mythread extends Thread{

}

他想要线程间共享变量,你的方法2对于他不合适。



可以的,i换成TestTongbu.i啊。

对。它的i静态的。是可以。