package cn.test.dxc.syc;
public class huizong {
//同步方法默认用this或者当前类class对象作为锁
public synchronized void methodA(){
//默认当前对象
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()+"方法A愉快的打印了"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void methodB(){
//锁当前对象
synchronized (this){
for (int i = 0; i <5 ; i++) {
System.out.println(Thread.currentThread().getName()+"方法B愉快的打印了"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void methodC(){
Object obj = new Object();//锁为自定义的对象
synchronized (obj){
for (int i = 0; i <5 ; i++) {
System.out.println(Thread.currentThread().getName()+"方法C愉快的打印了"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void methodD(){
synchronized (huizong.class){
//同步代码块用当前类信息对象
for (int i = 0; i <5 ; i++) {
System.out.println(Thread.currentThread().getName()+"方法D愉快的打印了"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static synchronized void methodE(){
//默认当前的类信息对象
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()+"方法E愉快的打印了"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
final huizong test = new huizong();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
test.methodA();
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
test.methodB();
}
});
thread2.start();
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
test.methodC();
}
});
thread3.start();
Thread thread4 = new Thread(new Runnable() {
@Override
public void run() {
test.methodD();
}
});
thread4.start();
Thread thread5 = new Thread(new Runnable() {
@Override
public void run() {
test.methodA();
}
});
thread5.start();
}
}
Synchronization code block and synchronization method
Guess you like
Origin blog.csdn.net/weixin_44695793/article/details/108475419
Recommended
Ranking