java 线程 学习笔记

1.创建

Thread thread = new Thread(task); //task为一个实现Runnable接口的任务实例

2.开始

thread.start();

3.线程池

ExecutorService executor = Executor.newFixedThreadPool(3);//创建一个最大线程数为3的线程池

executor.execute(任务1);

executor.execute(任务2);

executor.shutdown();//不再接受新任务,但会把当前的做完

4.synchronized关键字

synchronized(account){

account.deposit(1);

}

或者 public synchronized void deposit(double amount)在方法中加


5.利用加锁同步

  • private static Lock lock=new ReentrantLock();
  • private static Condition newDeposit=lock.newCondition();
  • //一个条件对应一个锁
  • lock.lock();获取锁
  • newDeposit().await();//让存款任务进入休眠,等待sign
  • newDeposit().signAll();//通知所有该条件的等待进程
  • lock.unlock();释放锁
  • 注意:条件是由锁创建的,为了调用条件的方法,必须首先拥有锁!!!

public class ThreadCooperation {

	private static Account2 account=new Account2();
	public static void main(String []args){
		ExecutorService executor=Executors.newFixedThreadPool(2);
		executor.execute(new DepositTask());
		executor.execute(new WithdrawTask());
		executor.shutdown();
		
		System.out.println("Thread 1\t\tThread 2\t\tBalance");
	
	}
	
	public static class DepositTask implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try{
			while(true){
				account.deposit((int)(Math.random()*10)+1);
				Thread.sleep(1000);
			}
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
		
	}
	public static class WithdrawTask implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			while(true){
				account.withdraw((int)(Math.random()*10+1));
				
			}
		}
		
	}
	
	
}
class Account2{
	private int balance=0;
	
	private static Lock lock=new ReentrantLock();
	private static Condition newDeposit=lock.newCondition();
	
	public int getBalance(){
		return balance;
	}
	
	public void withdraw(int amount){
		lock.lock();
		try{
			while(balance<amount){
				System.out.println("\t\t\tWait for a deposit");
				newDeposit.await();
			}
			balance-=amount;
			System.out.println("\t\t\tWithdraw "+amount+"\t\t"+getBalance());
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			lock.unlock();
			
		}
	}
	
	public void deposit(int amount){
		lock.lock();
		balance+=amount;
		System.out.println("Deposit "+amount+"\t\t\t\t\t"+getBalance());
		newDeposit.signalAll();
		
		lock.unlock();
		}
	
	
}


发布了78 篇原创文章 · 获赞 12 · 访问量 7万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览