File tree Expand file tree Collapse file tree
java-thread-demo/src/main/com/jay/otherThread Expand file tree Collapse file tree Original file line number Diff line number Diff line change 66 */
77public class MultiThread {
88
9+ private static class Thread1 implements Runnable {
910
11+ @ Override
12+ public void run () {
13+ //由于 Thread1和下面Thread2内部run方法要用同一对象作为监视器,如果用this则Thread1和Threa2的this不是同一对象
14+ //所以用MultiThread.class这个字节码对象,当前虚拟机里引用这个变量时指向的都是同一个对象
15+ synchronized (MultiThread .class ) {
16+ System .out .println ("进入 Threa1" );
17+ System .out .println ("Thead1 is waiting" );
18+ try {
19+ //释放锁有两种方式:(1)程序自然离开监视器的范围,即离开synchronized关键字管辖的代码范围
20+ //(2)在synchronized关键字管辖的代码内部调用监视器对象的wait()方法。这里使用wait方法
21+ MultiThread .class .wait ();
22+ } catch (InterruptedException e ) {
23+ e .printStackTrace ();
24+ }
25+ System .out .println ("Thread1 is going on....." );
26+ System .out .println ("Thread1 is being cover" );
27+ }
28+ }
29+ }
30+
31+ private static class Thread2 implements Runnable {
32+
33+ @ Override
34+ public void run () {
35+ synchronized (MultiThread .class ) {
36+ System .out .println ("进入 Thread2" );
37+ System .out .println ("Thread2 is sleep 10 second" );
38+ try {
39+ Thread .sleep (10000 );
40+ } catch (InterruptedException e ) {
41+ e .printStackTrace ();
42+ }
43+ System .out .println ("Thread2 is going on.....!" );
44+ System .out .println ("Thread2 is being cover!" );
45+ }
46+ }
47+ }
48+
49+ public static void main (String [] args ) {
50+ //启动Thread1
51+ new Thread (new Thread1 ()).start ();
52+ try {
53+ Thread .sleep (10000 );
54+ } catch (InterruptedException e ) {
55+ e .printStackTrace ();
56+ }
57+ new Thread (new Thread2 ()).start ();
58+ }
1059}
Original file line number Diff line number Diff line change 11
22 1、每个对象都有一个锁来控制同步访问,Synchroinized关键字可以和对象的锁交互,来实现
3- 同步方法或同步块。Sleep()方法住 ,使正在执行的线程继续往下执行(** 注意:sleep方法只让出了CPU,而并不会释放同步资源锁!!!** )
3+ 同步方法或同步块。Sleep()方法 ,使正在执行的线程继续往下执行(** 注意:sleep方法只让出了CPU,而并不会释放同步资源锁!!!** )
44 wait()方法则是指当前线程让自己暂时退出同步资源锁,以便其他正在等待该资源的线程得到该资源进而运行,只有调用了notify()方法,之前
55 调用wait()的线程才会解除wait状态,可以去参与竞争同步资源锁,进而得到执行。(** 注意:notify的作用相当于叫醒睡着的人,而并不会给他分配任务
66 ,就是说notify只是让之前调用wait的线程有权利重新参与线程的调度** );
1212 对象锁,进入等待队列,待调用notify()/notifyAll()唤醒指定的线程或者所有线程,才会
1313 进入锁池,不再次获得对象锁才会进入运行状态;
1414
15+
16+
1517
You can’t perform that action at this time.
0 commit comments