概念:同步代码块可以解决安全问题的根本原因在于那个对象快上,这个对象如同锁的功能。
多个线程需要同一个锁,才能锁的住,所以这个对象需要在run()方法外面声明。
同步的特点:
-
多线程
-
多线程使用同一个锁
-
能解决线程安全的问题。
同步的弊端:当线程很多时,其他线程会等待正在执行的线程执行完毕,这样会浪费资源,
降低CUP的使用效率。
实例:这个例子是启动多个对象的线程去修改同一个实例变量。public class lianxi { public static void main(String[] args) { demo obj=new demo(); Thread r=new Thread(new test(obj),"线程a"); Thread c=new Thread(new test(obj),"线程b"); r.start(); c.start(); } } class test extends Thread{ private demo b; public test(demo b) { this.b=b; } public test() { } @Override public void run() { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } kkk(); } public void kkk(){ synchronized(demo.class){ System.out.println(Thread.currentThread().getName()); while(true) { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(b.cc>0){ try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+",cc的值为:"+ b.cc); try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } b.cc--; }else{ break; } } } } } class demo{ public int cc=10; }
效果图: