当前位置: 移动技术网 > IT编程>开发语言>Java > 浅析Java多线程同步synchronized

浅析Java多线程同步synchronized

2019年07月19日  | 移动技术网IT编程  | 我要评论

单线程是安全的,因为线程只有一个,不存在多个线程抢夺同一个资源

代码例子:

public class singlethread {
	int num=10;
	public void add(){
		while(num<13){
			num++;
			try{
				thread.sleep(1000);
			}
			catch(exception e){
				system.out.println("中断");
			}
			system.out.println(num);
		}
	}
	public static void main(string[] args){
		thread thread = thread.currentthread(); //获取当前运行的线程对象
		thread.setname("单线程"); //线程重命名
		system.out.println(thread.getname()+"正在运行");
		singlethread st=new singlethread();
		st.add();
	}
}

多线程安全,synchronized同步代码块

synchronized(对象){}; //同步代码块

synchronized 返回值 方法名(){}; //同步方法

class one {
	 int num=10;
	 public void add(){ 
		synchronized(this){ //同步代码块,同步方法也可以实现效果synchronized void add(){};
		num++;
	  try {
	   thread.sleep(1000);
	  } catch (interruptedexception e) {
	  	system.out.println("中断");
	  }
	  system.out.println(num);
	  }
	 }
	}
	class two implements runnable{
	 one one = new one();
	 @override
	 public void run() {
		 one.add(); //调用add方法
	 }
	}
	public class synch{
	 public static void main(string[] args) {
		two two = new two();
	  thread t1 = new thread(two); //创建三个子线程
	  thread t2 = new thread(two);
	  thread t3 = new thread(two);
	  t1.start();
	  t2.start();
	  t3.start();
	 }
}

注意:观察去除synchronized关键字的运行结果区别!

正常运行结果:

11
12
13

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网