欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

synchronized测试

程序员文章站 2022-06-07 15:28:05
...

1、现有一个简单类UserVo,有两个打印方法。

package main.java.com.ji.test;

public class UserVo {

	private String name;
	private int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	public synchronized void printName() {
		System.out.println("name ....in  ....");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("name .... = ");
	}

	
	public synchronized void printAge() {
		System.out.println("age .... in  ....");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("age .... = ");
	}
}

 另写了一个测试类

 

 

package main.java.com.ji.test;

public class MyThread implements Runnable {

	private UserVo userVo;
	
	public MyThread(UserVo userVo) {
		this.userVo = userVo;
	}
	@Override
	public void run() {
		userVo.printName();
	}

	
	
	public static void main(String[] args) {
		UserVo userVo = new UserVo();
		userVo.setAge(99);
		userVo.setName("admin....xxx");

		UserVo userVo2 = new UserVo();
		userVo2.setAge(99222);
		userVo2.setName("222admin....xxx");
		for (int i = 0; i < 10; i++) {
			new Thread(new MyThread(userVo)).start();
			new Thread(new MyThreadAge(userVo)).start();
		}
	}
}

class MyThreadAge implements Runnable {

	private UserVo userVo;
	
	public MyThreadAge(UserVo userVo) {
		this.userVo = userVo;
	}
	@Override
	public void run() {
		userVo.printAge();
	}
}

 

 

2、如果想执行

for (int i = 0; i < 10; i++) {
			new Thread(new MyThread(userVo)).start();
			new Thread(new MyThreadAge(userVo)).start();
		}

 循环的时候,每个单独的printName和printAge不被打断的话,两个方法前需加关键字synchronized

 

3、、如果想执行

for (int i = 0; i < 10; i++) {
			new Thread(new MyThread(userVo)).start();
			new Thread(new MyThreadAge(userVo2)).start();
		}

 循环的时候,每个单独的printName和printAge不被打断的话,两个方法前需加关键字 static synchronized