1. 两种方式实现资源共享,synchronized包含共享资源,synchronized修饰共享资源方法
2.
synchronized ("") {
//.................
}
3.
public synchronized void doIt(){
//..............
}
4. 示例:
package edu.learn.foundation;
public class SynchronizedDemo implements Runnable {
int index=10;
@Override
public void run() {
while(true){
synchronized ("") {
System.out.println(index);
--index;
if(index<=0){
return;
}
}
}
}
}
package edu.learn.foundation;
public class SynchronizedFuncDemo implements Runnable {
int index=20;
public synchronized void doIt(){
while (true) {
System.out.print(index);
--index;
if(index<=0){
return;
}
}
}
@Override
public void run() {
this.doIt();
}
}
package edu.learn.foundation;
public class Test {
public static void main(String[] args) {
SynchronizedDemo aDemo=new SynchronizedDemo();
Thread aThread = new Thread(aDemo);
//SynchronizedDemo bDemo=new SynchronizedDemo();
Thread bThread = new Thread(aDemo);
aThread.start();
bThread.start();
SynchronizedFuncDemo aFuncDemo= new SynchronizedFuncDemo();
Thread aFuncThread = new Thread(aFuncDemo);
Thread bFuncThread = new Thread(aFuncDemo);
aFuncThread.start();
bFuncThread.start();
}
}
6. 结果:
10
9
8
7
6
5
4
3
2
1
0
20191817161514131211109876543210