java多线程与线程同步
JAVA 线程同步的几种方式
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SynTest {
public static void main(String[] args) throws Exception{
//1.两个线程共享变量,变量值不确定
//nonsyn();
//2.使用线程同步方法:synchronized save1
//syn();
//3.使用volatile 线程同步: volatile int account
//vola();
//4.使用重入锁ReentrantLock: save2() , new lock
//lock();
//5.使用局部变量ThreadLocal线程同步: ThreadLocal<int>
Bank2 b=new Bank2();
NewThread2 t=new NewThread2(b);
Thread t1=new Thread(t,"t1");
t1.start();
Thread t2=new Thread(t,"t2");
t2.start();
t1.join();
t2.join();
System.out.println("非同步 account="+b.get());
}
static void nonsyn()throws Exception{
Bank b=new Bank();
NewThread t=new NewThread(b);
Thread t1=new Thread(t,"t1");
t1.start();
Thread t2=new Thread(t,"t2");
t2.start();
t1.join();
t2.join();
System.out.println("非同步 account="+b.get());
}
static void syn()throws Exception{
Bank b=new Bank();
NewThread t=new NewThread(b);
Thread t1=new Thread(t,"t1");
t1.start();
Thread t2=new Thread(t,"t2");
t2.start();
t1.join();
t2.join();
System.out.println("非同步 account="+b.get());
}
static void vola()throws Exception{
Bank b=new Bank();
NewThread t=new NewThread(b);
Thread t1=new Thread(t,"t1");
t1.start();
Thread t2=new Thread(t,"t2");
t2.start();
t1.join();
t2.join();
System.out.println("非同步 account="+b.get());
}
static void lock()throws Exception{
Bank b=new Bank();
NewThread t=new NewThread(b);
Thread t1=new Thread(t,"t1");
t1.start();
Thread t2=new Thread(t,"t2");
t2.start();
t1.join();
t2.join();
System.out.println("非同步 account="+b.get());
}
}
class Bank{
private int account;
//private volatile int account;
private Lock lock=new ReentrantLock();
public void save(int money){
this.account+=money;
}
// public synchronized void save1(int money){
// this.account+=money;
// }
public void save2(int money){
lock.lock();
this.account+=money;
lock.unlock();
}
public int get(){
return this.account;
}
}
class NewThread implements Runnable{
private Bank bank;
public NewThread(Bank bank){
this.bank=bank;
}
public void run() {
for(int i=0;i<30000;i++){
//bank.save(10); //使用volatile 同步
//bank.save1(10); //使用synchronized 同步
bank.save2(10);//使用lock同步
System.out.println("非同步 account="+bank.get());
}
//System.out.println( " account="+bank.get());//结果不确定20000
}
}
class Bank2{
private ThreadLocal<Integer> account=new ThreadLocal<Integer>(){
protected Integer initialValue(){
return 0;
}
};
public void save(int money){
account.set(account.get()+money);
}
public int get(){
return this.account.get();
}
}
class NewThread2 implements Runnable{
private Bank2 bank;
public NewThread2(Bank2 bank){
this.bank=bank;
}
public void run() {
for(int i=0;i<30000;i++){
bank.save(10);
//System.out.println(Thread.currentThread().getName()+"同步 account="+bank.get());
}
System.out.println(Thread.currentThread().getName()+"同步 account="+bank.get());
}
}
ThreadLocal 线程局部变量如何线程通信呢?
上一篇: spring 线程池