一 同步的概念
线程的同步是为了防止多个线程访问一个数据对象时,对数据造成的破坏。
例如:两个线程ThreadA、ThreadB都操作同一个对象Foo对象,并修改Foo对象上的数据。
MyRunnable.java
1 package Thread; 2 public class MyRunnable implements Runnable{ 3 private Foo foo=new Foo(); 4 public static void main(String[] args){ 5 MyRunnable r=new MyRunnable(); 6 Thread ta=new Thread(r,"Thread-A"); 7 Thread tb=new Thread(r,"Thread-B"); 8 ta.start(); 9 tb.start(); 10 } 11 public void run(){ 12 for(int i=0;i<3;i++){ 13 this.fix(30); 14 try{ 15 Thread.sleep(1); 16 } 17 catch(InterruptedException e){ 18 e.printStackTrace(); 19 } 20 System.out.println(Thread.currentThread().getName()+":当前foo对象的值="+foo.getX()); 21 } 22 } 23 public int fix(int y){ 24 return foo.fix(y); 25 } 26 }