java 并发主题详解

本文深入探讨Java并发编程的关键概念和技术,包括线程定义、共享资源管理、线程间协作及性能优化等核心主题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

并发是计算机科学里的一个基本课题,本篇文章将针对JAVA的并发分四个主题讨论一下多线程在JAVA里的写法和用处。四个课题分别是:线程的定义;共享受限资源;线程间协作;性能调优。

  1 线程定义:

  new Threadnew Runnable(){

  public void run() {

  /*

  * 希望线程做什么事情,在这里写就好;对本写法进行拆分,可以有别的写法

  */

  }

  })。start();

  2 共享资源受限:

  说白了就对共享的资源加锁,让同时只有一个线程可以访问该资源,锁从类型上分为三种:对象锁、类锁、代码块锁。

  2.1 对象锁

  public class Counter {

  private Long id = 0L;

  public synchronized void increase(){

  id++;

  }

  public synchronized void printCounter(){

  System.out.printlnthis.id);

  }

  }

  类Counter中有两个同步方法:increase()、printCounter()。在同一个对象上,两个方法不能同时执行,互相排斥。不同对象上当然可以。

  2.2 类锁

  public class Generator {

  private static Long id = 0L;

  public synchronized static void next(){

  id++;

  }

  public synchronized static void print(){

  System.out.printlnThread.currentThread()。getName());

  System.out.printlnid);

  }

  }

  类Generator中有两个同步方法:next()、print()。在同一个对象上,两个方法不能同时执行,互相排斥。不同对象上也不能同时执行,互相排斥。

  2.3 代码块锁

  public class CatalogContentSyn extends HttpServlet {

  protected void serviceHttpServletRequest req, HttpServletResponse resp

  throws ServletException, IOException {

  synchronized "lockcata" {

  /*

  * 这里有一个读写数据库的操作,所有访问到这个地方的时候,

  * 前一个访问必须先执行完,后到的访问才能执行。如果前一个访问没有完成本块代码,

  * 后到访问阻塞。

  */

  }

  }

  }

  前一个访问必须先执行完,后到的访问才能执行。如果前一个访问没有完成本块代码, 后到访问阻塞。

  3 线程间协作:

  public class ListStack {

  private  ArrayList<Integer>

  list = new ArrayList<Integer>100);

  private Boolean hasWait = false;

  /*

  * 压栈方法,如果栈中有数据,并且有线程在等待,唤醒其它线程

  */

  public synchronized  void push(){

  Random rand = new Random();

  list.addrand.nextInt10000));

  iflist.size() > 0 && hasWait{

  this.notifyAll();

  hasWait = false;

  }

  }

  /*

* 出栈方法:从栈里那第一条数据,如果发现没有数据,线程等待

  */

  public synchronized  Integer pop(){

  Integer firstElement = null;

  ifnull != list && list.size() > 0{

  firstElement = list.get0);

  list.remove0);

  }else{

  try {

  hasWait = true;

  this.wait();

  } catch InterruptedException e {

  e.printStackTrace();

  }

  }

  return firstElement;

  }

  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值