首页 > 代码库 > 多线程之同步Synchronized
多线程之同步Synchronized
在java中synchronized是多个线程共享同一段代码的锁。
当有多个线程并发执行同一块代码块时,加锁可以让一段时间内只有一个线程在执行,保证了业务的原子操作。
例如下面:
package andy.thread.traditional.test; /** * @author Zhang,Tianyou * @version 2014年11月8日 下午11:02:53 */ // 使用synchronized加同步锁 public class ThreadSynchronizedTest { public static void main(String[] args) { A a = new A(); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } a.printfA(Thread.currentThread().getName() + "hello, my is A"); } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } a.printfA(Thread.currentThread().getName() + "hello, my is B"); } } }).start(); } static class A { public void printfA(String name) { for (int i = 0; i < name.length(); i++) { System.out.print(name.charAt(i)); } System.out.println(); } } }
Thread-1hello, my is B Thread-1hello, my is B Thread-0hello, my is A ThThread-0hello, my is A read-1hello, my is B Thread-1helTlhreoad-0hello, my is A , my is B Thread-0hello, my is A Thread-1hello, my is B Thread-0hello, my is A
这是为了防止多线程并发执行时,确保只有一个在使用我们可以加同步锁。
synchronized(name){
// 加锁的代码块, name为锁标志
}
syschronized 可以加在方法里和方法内:
package andy.thread.traditional.test; /** * @author Zhang,Tianyou * @version 2014年11月8日 下午11:02:53 */ // 使用synchronized加同步锁 public class ThreadSynchronizedTest { public static void main(String[] args) { A a = new A(); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } a.printfA(Thread.currentThread().getName() + "hello, my is A"); } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } a.printfA(Thread.currentThread().getName() + "hello, my is B"); } } }).start(); } static class A { public void printfA(String name) { synchronized (A.class) { for (int i = 0; i < name.length(); i++) { System.out.print(name.charAt(i)); } System.out.println(); } } public synchronized void printfB(String name) { for (int i = 0; i < name.length(); i++) { System.out.print(name.charAt(i)); } System.out.println(); } } }
运行效果如下:
Thread-1hello, my is B Thread-0hello, my is A Thread-1hello, my is B Thread-0hello, my is A Thread-1hello, my is B Thread-0hello, my is A Thread-1hello, my is B Thread-0hello, my is A Thread-1hello, my is B Thread-0hello, my is A Thread-1hello, my is B Thread-0hello, my is A Thread-1hello, my is B Thread-0hello, my is A Thread-1hello, my is B
多线程之同步Synchronized
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。