Java多线程同步synchronized

版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创!


恰饭广告




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

代码例子:

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

原文链接:https://www.idaobin.com/archives/839.html

让我恰个饭吧.ヘ( ̄ω ̄ヘ)

支付宝 ——————- 微信
图片加载中图片加载中



恰饭广告

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

5 × 2 =