要想顺序输出1,2,3,下面的代码有什么问题? 怎么理解? 谢谢!
public class MultiShare {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new MyThread().start();
new MyThread().start();
new MyThread().start();
}
}
class MyThread extends Thread{
static int j=0;
public synchronized void run(){
j ++;
System.out.println(j );
}
}
------解决思路----------------------
new MyThread().run();
new MyThread().run();
new MyThread().run();
------解决思路----------------------
synchronized方法,每个类实例对应一把锁,你new了三个实例,所以每个实例都拿到了自己的锁,顺序就不一定了。
可以试试这个全局锁
class MyThread extends Thread{
static int j=0;
public void run(){
synchronized (MyThread.class) {
j ++;
System.out.println(j );
}
}
}
------解决思路----------------------
或者这样public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt).start();
new Thread(mt).start();
new Thread(mt).start();
}