Java语言的关键字,可用来给对象和方法或者代码块加锁,当它锁定一个方法或者一个代码块的时候,同一时刻最多只有一个线程执行这个段代码。当两个并发线程访问同一个对象object中的这个加锁同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。然而,当一个线程访问object的一个加锁代码块时,另一个线程仍然可以访问该object中的非加锁代码块。
以上是百度百科中的解释,下面来用代码举例说明;
首先写一个线程类:myThread.class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
package
com.liuyang.jxc_test.thread;
/**
* 线程的学习和测试
*
* @author dr.con
*
*/
public
class
myThread
extends
Thread {
private
static
Integer count =
0
;
/**
* 覆盖run方法,实现自己的功能
*/
@Override
public
void
run() {
int
i;
for
(i =
0
; i <
100
; i++) {
count = count +
1
;
System.out.println(
"My name is "
+ getName() +
" count= "
+ count);
}
try
{
sleep(
10
);
}
catch
(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public
myThread(String name) {
super
(name);
}
}
|
然后书写测试类:mulThread.class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package
com.liuyang.jxc_test.thread;
/**
* 测试线程用的
*
* @author dr.con
*
*/
public
class
mulThread {
public
static
void
main(String[] args) {
myThread firstThread =
new
myThread(
"First Thread"
);
myThread secondThread =
new
myThread(
"Second Thread"
);
firstThread.start();
secondThread.start();
System.out.println(
"主线程结束"
);
}
}
|
运行代码:
结果发现,最后线程的count可能是不连续的,最终也不到200;
My name is Second Thread count = 107
My name is Second Thread count = 108
My name is Second Thread count = 109
My name is Second Thread count = 110
My name is Second Thread count = 111
My name is First Thread count = 119
My name is First Thread count = 120
My name is First Thread count = 121
My name is First Thread count = 122
My name is First Thread count = 123
修改线程类myThread.class,增加synchronized关键字:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
package
com.liuyang.jxc_test.thread;
/**
* 线程的学习和测试
*
* @author dr.con
*
*/
public
class
myThread
extends
Thread {
private
static
Integer count =
0
;
/**
* 覆盖run方法,实现自己的功能
*/
@Override
public
void
run() {
synchronized
(
this
) {
int
i;
for
(i =
0
; i <
100
; i++) {
count = count +
1
;
System.out.println(
"My name is "
+ getName() +
" count = "
+ count);
}
try
{
sleep(
100
);
}
catch
(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public
myThread(String name) {
super
(name);
}
}
|
再执行测试类后,所有的count从1开始按照顺序执行,不在出现穿插等错误;