标签:
Java提供了两种创建线程方法:
线程同步
synchronized(object){ }
1 package com.xhj.thread; 2 3 /** 4 * 线程同步的运用 5 * 6 * @author XIEHEJUN 7 * 8 */ 9 public class SynchronizedThread { 10 11 class Bank { 12 13 private int account = 100; 14 15 public int getAccount() { 16 return account; 17 } 18 19 /** 20 * 用同步方法实现 21 * 22 * @param money 23 */ 24 public synchronized void save(int money) { 25 account += money; 26 } 27 28 /** 29 * 用同步代码块实现 30 * 31 * @param money 32 */ 33 public void save1(int money) { 34 synchronized (this) { 35 account += money; 36 } 37 } 38 } 39 40 class NewThread implements Runnable { 41 private Bank bank; 42 43 public NewThread(Bank bank) { 44 this.bank = bank; 45 } 46 47 @Override 48 public void run() { 49 for (int i = 0; i < 10; i++) { 50 // bank.save1(10); 51 bank.save(10); 52 System.out.println(i + "账户余额为:" + bank.getAccount()); 53 } 54 } 55 56 } 57 58 /** 59 * 建立线程,调用内部类 60 */ 61 public void useThread() { 62 Bank bank = new Bank(); 63 NewThread new_thread = new NewThread(bank); 64 System.out.println("线程1"); 65 Thread thread1 = new Thread(new_thread); 66 thread1.start(); 67 System.out.println("线程2"); 68 Thread thread2 = new Thread(new_thread); 69 thread2.start(); 70 } 71 72 public static void main(String[] args) { 73 SynchronizedThread st = new SynchronizedThread(); 74 st.useThread(); 75 } 76 77 }
//只给出要修改的代码,其余代码与上同 class Bank { //需要同步的变量加上volatile private volatile int account = 100; public int getAccount() { return account; } //这里不再需要synchronized public void save(int money) { account += money; } }
class Bank { private int account = 100; //需要声明这个锁 private Lock lock = new ReentrantLock(); public int getAccount() { return account; } //这里不再需要synchronized public void save(int money) { lock.lock(); try{ account += money; }finally{ lock.unlock(); } } }
5、使用局部变量实现线程同步
public class Bank{ //使用ThreadLocal类管理共享变量account private static ThreadLocal<Integer> account = new ThreadLocal<Integer>(){ @Override protected Integer initialValue(){ return 100; } }; public void save(int money){ account.set(account.get()+money); } public int getAccount(){ return account.get(); } }
标签:
原文地址:http://www.cnblogs.com/arbitrary/p/5262597.html