在多线程运行中,常常使用到synchronized同步锁处理多线程安全问题。关于synchronized中的相关概念和使用方法请看Thread中的同步锁synchronized(https://blog.csdn.net/luo_boke/article/details/99822040)。
如下是一段代码:
public class MainTest {
public static void main(String[] args) {
// 创建10个线程来调用【同一个】TestForSynchronized实例(对象)
MyTest temp = new MyTest();
for (int index = 0; index < 10; index++) {
MyThread thread = new MyThread(temp);
thread.start();
}
}
}
class MyThread extends Thread {
private MyTest testObject;
public MyThread(MyTest testObject) {
this.testObject = testObject;
}
@Override
public void run() {
System.out.println(" 线程名" + Thread.currentThread().getName() + "- ************** " + testObject.commonPrint());
System.out.println(" 线程名" + Thread.currentThread().getName() + "- ############## " + testObject.print1());
}
}
class MyTest {
public int count = 0;
//print1 方法 -synchronized块(对象级,这里是对象不是地址引用)
public int print1() {
synchronized (this) {
count++;
}
return count;
}
//print2 方法 -synchronized块(类级别)
public int print2() {
synchronized (com.xuanyuan.makefun.codingstudy.Test.class) {
count++;
}
return count;
}
//print3 方法 -synchronized 方法
public synchronized int print3() {
count++;
return count;
}
//普通方法
public int commonPrint() {
return count;
}
}
经过运行其结果为:
线程名Thread-0- ************** 0
线程名Thread-0- ############## 1
线程名Thread-2- ************** 1
线程名Thread-3- ************** 1
线程名Thread-3- ############## 3
线程名Thread-2- ############## 2
线程名Thread-6- ************** 3
线程名Thread-1- ************** 3
线程名Thread-1- ############## 5
线程名Thread-4- ************** 5
线程名Thread-4- ############## 6
线程名Thread-7- ************** 3
线程名Thread-7- ############## 7
线程名Thread-6- ############## 4
线程名Thread-5- ************** 7
线程名Thread-5- ############## 8
线程名Thread-9- ************** 8
线程名Thread-9- ############## 9
线程名Thread-8- ************** 9
线程名Thread-8- ############## 10
我将其中的方法进行自定义
System.out.println(" 线程名" + Thread.currentThread().getName() + "- ************** " + testObject.commonPrint());
System.out.println(" 线程名" + Thread.currentThread().getName() + "- ############## " + testObject.print1());
如线程Thread-0调用commonPrint()设定为A0,调用print1()认定为B0。那么根据count的显示结果,可以推测方法的调用顺序为如下:
A0 >> B0 >> A2 >> A3 >> B2 >> B3 >> A6 >> A1 >> A7 >> B6 >> B1 >> A4 >> B4 >> B7 >> A5 >> B5 >> A9 >> B9 >> A8 >> B8
我们看到的打印信息和现在的执行顺序不一样,是因为在多线程中每个线程的执行时间是和顺序是由CPU决定,所以打印方法是展示给我们的数据是随机的。
关于Thread的其他知识如:
Thread的常用方法解析:https://blog.csdn.net/luo_boke/article/details/99565397