今天再android_serial_port中看到了关键字 synchronized;因为刚好在学java和android,所以就查了一下它的用法:
于是把代码中的一小段代码拿了出来,做了一下修改,测试了下,结果出现的情况:
1 public class syncThreadDemo { 2 3 public static void main(String[] args) { 4 // TODO Auto-generated method stub 5 /*测试1*/ 6 // Account account = new Account("zhang san", 10000.0f); 7 // AccountOperator accountOperator = new AccountOperator(account); 8 // 9 // final int THREAD_NUM = 5;10 // Thread threads[] = new Thread[THREAD_NUM];11 // for (int i = 0; i < THREAD_NUM; i ++) {12 // threads[i] = new Thread(accountOperator, "Thread" + i);13 // threads[i].start();14 // }15 16 /*测试2*/17 18 Thread thread1=new Thread(new syncThreadDemo().new SendingThread("send1"),"thread1");19 thread1.start();20 Thread thread2=new Thread(new syncThreadDemo().new ReceiveThread("recv1"),"thread2");21 thread2.start();22 23 }24 /*创建一个内部类来测试synchronized锁定一个对象*/25 static Object mByteReceivedBackSemaphore = new Object();26 27 private class SendingThread implements Runnable{28 private int i=0;29 private String name;30 //创建一个构造函数31 public SendingThread(String strName) {32 // TODO Auto-generated constructor stub33 this.name=strName;34 }35 36 @Override37 public void run(){38 while (i<10) {39 synchronized (mByteReceivedBackSemaphore) {40 try {41 // Wait for 100ms before sending next byte, or as soon as42 // the sent byte has been read back.43 System.out.println(Thread.currentThread().getName()+": wait");44 mByteReceivedBackSemaphore.wait(100);45 i++;46 System.out.println(Thread.currentThread().getName()+":"+i);47 } 48 catch (Exception e) {49 // TODO: handle exception50 } 51 }52 }53 }54 }55 56 private class ReceiveThread implements Runnable{57 private int j=0;58 private String name;59 60 public ReceiveThread(String strName) {61 // TODO Auto-generated constructor stub62 this.name=strName;63 }64 65 @Override66 public void run(){67 while(j<10){68 synchronized(mByteReceivedBackSemaphore){69 System.out.println(Thread.currentThread().getName()+": notify");70 mByteReceivedBackSemaphore.notify(); 71 j++;72 System.out.println(Thread.currentThread().getName()+":"+j);73 }74 }75 }76 }77 }
测试结果:
thread1: waitthread2: notifythread2:1thread2: notifythread2:2thread2: notifythread2:3thread2: notifythread2:4thread2: notifythread2:5thread2: notifythread2:6thread2: notifythread2:7thread2: notifythread2:8thread2: notifythread2:9thread2: notifythread2:10thread1:1thread1: waitthread1:2thread1: waitthread1:3thread1: waitthread1:4thread1: waitthread1:5thread1: waitthread1:6thread1: waitthread1:7thread1: waitthread1:8thread1: waitthread1:9thread1: waitthread1:10