zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    chm文件生成
    java基础--集合
    java基础--多线程
    nexus
    java基础--IO流
    http与https
    java基础--数据结构
    mysql 优化
    maven依赖和传递
    java设计模式
  • 原文地址:https://www.cnblogs.com/kunpengit/p/2793007.html
Copyright © 2011-2022 走看看