多线程的同步

来源:互联网 发布:印度山地师 知乎 编辑:程序博客网 时间:2024/06/06 04:27

一、为什么使用线程同步
线程同步是为了防止多个线程访问一个数据对象时,对数据造成破坏
二、多线程案例
package cn.thread;public class Boo {private int x = 100;    public int getX() {        return x;    }    public synchronized int fix(int y) {        x = x - y;        System.out.println(Thread.currentThread().getName() + " : 当前boo对象的y值= " + x);        return x;    }//  //同步代码块//  public int fix(int y) {//      synchronized (this) {//           x = x - y;//           System.out.println(Thread.currentThread().getName() + " : 当前boo对象的y值= " + x);//      }//      //      return x;//  }}

调用时
 
package cn.thread;public class MyRunnable implements Runnable {    private Boo foo = new Boo();    public static void main(String[] args) {        MyRunnable run = new MyRunnable();        Thread ta = new Thread(run, "Thread-A");        Thread tb = new Thread(run, "Thread-B");        ta.start();        tb.start();    }    public void run() {        for (int i = 0; i < 3; i++) {            this.fix(30);            try {                Thread.sleep(1);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    public int fix(int y) {        return foo.fix(y);    }}
注意的问题:
1、只能同步方法,不能同步对象和类
2、如果线程试图进入同步方法,而其锁已经被占用,则线程在该对象上被阻塞。

0 0