首页 > 代码库 > java synchronized(一)
java synchronized(一)
java synchronized主要用于控制线程同步,中间有很多小的细节,知识,这里我简单的整理一下,做个记录。主要用于方法和代码块的控制
先说说方法控制
模拟银行存款和取款,创建一个Account类,两个属性,一个name和accout。先存1w进去,在用一100个线程取钱1k和存1k。等待所有线程结束后,输出account。没有synchronized控制会造成account不等于1w。使用了synchronized结果正确,性能降低了很多。下面贴一下代码
参考:http://www.cnblogs.com/devinzhang/archive/2011/12/14/2287675.html
Account.java
1 package com.gxf.thread; 2 3 public class Account { 4 public String name; 5 public float amount; 6 7 public Account(String name, float amount){ 8 this.name = name; 9 this.amount = amount;10 }11 12 /**13 * 模拟存钱14 * @param amt15 */16 public synchronized void deposit(float amt){17 float tmp = amount;18 tmp += amt;19 try {20 Thread.sleep(100);21 } catch (InterruptedException e) {22 23 e.printStackTrace();24 }25 this.amount = tmp;26 }27 28 /**29 * 模拟取钱30 * @param amt31 */32 public synchronized void withdraw(float amt){33 float tmp = amount;34 tmp -= amt;35 try {36 Thread.sleep(100);37 } catch (InterruptedException e) {38 39 e.printStackTrace();40 }41 42 amount = tmp;43 }44 }
测试类AccountTest.java
1 package com.gxf.thread; 2 3 public class AccountTest { 4 5 public static void main(String[] args) { 6 final int NUM_THREADS = 5; //线程总数 7 Thread threads[] = new Thread[NUM_THREADS]; 8 final Account zhangsan = new Account("zhangsan", 10000); //张三存1w到银行 9 10 //1000个线程对张三账户进行存钱1k和取1k11 for(int i = 0; i < NUM_THREADS; i++){12 threads[i] = new Thread(new Runnable(){13 14 @Override15 public void run() {16 zhangsan.deposit(1000);17 zhangsan.withdraw(1000);18 }19 20 });21 threads[i].start(); //线程开始22 }23 //等待所有线程结束24 for(int i = 0; i < NUM_THREADS; i++){25 try {26 threads[i].join(); //等待该线程结束27 } catch (InterruptedException e) {28 // TODO Auto-generated catch block29 e.printStackTrace();30 }31 }32 System.out.println("account = " + zhangsan.amount);33 }34 35 }
还有就是修饰一个代码块
参考:http://javacrazyer.iteye.com/blog/759300/
类LockThread向屏幕输出1-9
两个线程同时访问lockThread向屏幕输出的方法,不同步将会输出如:1 1 2 2 3 3...用了同步输出如:1 2 3 ...1 2 3...
LockThread.java
1 package com.gxf.thread; 2 3 public class LockThread implements Runnable { 4 5 @Override 6 public void run() { 7 synchronized(this){ 8 for(int i = 1; i < 10; i++){ 9 System.out.println(i);10 try {11 Thread.sleep(1000);12 } catch (InterruptedException e) {13 14 e.printStackTrace();15 }16 }17 }18 19 }20 21 }
测试代码
LockThreadTest.java
1 package com.gxf.thread; 2 3 public class LockThreadTest { 4 5 public static void main(String[] args) { 6 LockThread lockThread = new LockThread(); 7 Thread thread1 = new Thread(lockThread); 8 Thread thread2 = new Thread(lockThread); 9 10 thread1.start();11 thread2.start();12 13 }14 15 }
ps:我也没检查synchronized拼对没有~
java synchronized(一)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。