(原)测试 Java中Synchronized锁定对象的用法
今天再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 stub
33 this.name=strName;
34 }
35
36 @Override
37 public void run(){
38 while (i<10) {
39 synchronized (mByteReceivedBackSemaphore) {
40 try {
41 // Wait for 100ms before sending next byte, or as soon as
42 // 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 exception
50 }
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 stub
62 this.name=strName;
63 }
64
65 @Override
66 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 }
View Code
测试结果:
thread1: waitthread2: notify
thread2:1
thread2: notify
thread2:2
thread2: notify
thread2:3
thread2: notify
thread2:4
thread2: notify
thread2:5
thread2: notify
thread2:6
thread2: notify
thread2:7
thread2: notify
thread2:8
thread2: notify
thread2:9
thread2: notify
thread2:10
thread1:1
thread1: wait
thread1:2
thread1: wait
thread1:3
thread1: wait
thread1:4
thread1: wait
thread1:5
thread1: wait
thread1:6
thread1: wait
thread1:7
thread1: wait
thread1:8
thread1: wait
thread1:9
thread1: wait
thread1:10
View Code
以上是 (原)测试 Java中Synchronized锁定对象的用法 的全部内容, 来源链接: utcz.com/z/392907.html