多线程日记(17.5.2two)synchronized的基本规则
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程日记(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的基本规则的主要内容,如果未能解决你的问题,请参考以下文章