首页 > 代码库 > 多线程日记(17.5.2two)synchronized的基本规则
多线程日记(17.5.2two)synchronized的基本规则
synchronized关键字
1)当有一条线程访问某个对象的synchronized的方法或代码块时,其它线程进行访问将会被阻塞;
2)当有一条线程访问某个对象的synchronized的方法或代码块时,其它线程访问该对象的非同步代码块时不会被阻塞;
3)当有一条线程访问某个对象的synchronized的方法或代码块时,其它线程访问该对象的其它同步代码块时将会被阻塞。
第一条规则
public class Test { public static void main(String[]args){ //create object for the two threads NewThread obj=new NewThread(); //create new thread Thread thread1=new Thread(obj,"t1"); Thread thread2=new Thread(obj,"t2"); thread1.start(); thread2.start(); } } class NewThread implements Runnable{ @Override public void run(){ synchronized(this){ try{ for(int i=0;i<3;i++){ Thread.sleep(100); System.out.println(Thread.currentThread().getName()+":"+(i+1)); } }catch(InterruptedException e){ System.out.println("error"); } } } }
第二条规则:
public class Test { public static void main(String[]args){ final Demo demo=new Demo(); //create first thread Thread thread1=new Thread(new Runnable(){ @Override public void run(){ demo.synchronizedThread(); } },"t1"); //create second thread Thread thread2=new Thread(new Runnable(){ @Override public void run(){ demo.unsynchronizedThread(); } },"t2"); thread1.start(); thread2.start(); } } class Demo{ //synchronized method public void synchronizedThread(){ synchronized(this){ try{ for(int i=0;i<3;i++){ System.out.println(Thread.currentThread().getName()+":"+(i+1)); Thread.sleep(100); } }catch(InterruptedException e){ System.out.println("error"); } } } //unsynchronized method public void unsynchronizedThread(){ try{ for(int i=0;i<3;i++){ System.out.println(Thread.currentThread().getName()+":"+(i+1)); Thread.sleep(100); } }catch(InterruptedException e){ System.out.println("error"); } } }
第三条规则:
public class Test { public static void main(String[]args){ final Demo demo=new Demo(); //create first thread Thread thread1=new Thread(new Runnable(){ @Override public void run(){ demo.synchronizedThread(); } },"t1"); //create second thread Thread thread2=new Thread(new Runnable(){ @Override public void run(){ demo.samesynchronizedThread(); } },"t2"); thread1.start(); thread2.start(); } } class Demo{ //synchronized method public void synchronizedThread(){ synchronized(this){ try{ for(int i=0;i<3;i++){ System.out.println(Thread.currentThread().getName()+":"+(i+1)); //sleep(100) Thread.sleep(100); } }catch(InterruptedException e){ System.out.println("error"); } } } //synchronized method public void samesynchronizedThread(){ synchronized(this){ try{ for(int i=0;i<3;i++){ System.out.println(Thread.currentThread().getName()+":"+(i+1)); //sleep(100) Thread.sleep(100); } }catch(InterruptedException e){ System.out.println("error"); } } } }
synchronized的方法和代码块
方法:public synchronized void method1(){}
代码块:class Lei{synchronized(this)}
参考自:http://www.cnblogs.com/skywang12345/p/3479202.html#p3
多线程日记(17.5.2two)synchronized的基本规则
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。