java线程 同步与锁定
public class Foo { private int x = 100; public synchronized int getX(){ System.out.println("getx"+x); return x; } public int getY(int y){
synchronized (this) {
x=x-y;
System.out.println("gety"+x);
return x;
}
}}
public class MyThread implements Runnable{ private Foo foo= new Foo(); public static void main(String[] args) { MyThread m = new MyThread(); Thread ta = new Thread(m,"thread A"); Thread tb = new Thread(m,"thread B"); ta.start(); tb.start(); } @Override public void run() { for (int i = 0; i < 3; i++) { this.get(30); try { Thread.sleep(20); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":"+foo.getX()); } } public int get(int y){ return foo.getY(y); } }
以上代码只有在加锁时才能保证数据的合理性,两个线程用锁来控制对Foode的访问。
要同步静态方法:需要一个用于整个类对象的锁,这个对象就是这个类(XXX.class)
public int getY(int y){
synchronized (xxx.class) {
x=x-y;
System.out.println("gety"+x);
return x;
}