java线程通信,解决线程之间的交互问题
2015-11-29 21:40
489 查看
线程通信:
注意三个都是Object的方法 并且都必须在synchronzied代码块和安全方法下使用否则会报异常
wiat:使当前线程挂起,释放锁,其他线程可以参与进来共享其数据。
notify:唤醒当前线程,让线程握住锁,其他线程无法参与进来。
notifyall:唤醒所有的线程。
下面为活生生列子一枚:
public class ThreadTest {
public static void main(String[] args) {
Account acc=new Account();
Custom c1=new Custom(acc);
Custom c2=new Custom(acc);
c1.setName("线程1");
c2.setName("线程2");
c1.start();
c2.start();
}
}
class Custom extends Thread{
Account ac;
public Custom(Account acc) {
this.ac=acc;
}
public void run(){
try {
for(int i=0;i<3;i++){
ac.deposit(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Account{
double balance;
public Account(){}
public synchronized void deposit(double many) throws InterruptedException{
notify();//唤醒线程
balance+=many;
Thread.currentThread().sleep(10);
System.out.println(Thread.currentThread().getName()+":"+balance);
wait();//挂起线程
}
}
打印结果 为交替执行:
线程1:1000.0
线程2:2000.0
线程1:3000.0
线程2:4000.0
线程1:5000.0
线程2:6000.0
注意三个都是Object的方法 并且都必须在synchronzied代码块和安全方法下使用否则会报异常
wiat:使当前线程挂起,释放锁,其他线程可以参与进来共享其数据。
notify:唤醒当前线程,让线程握住锁,其他线程无法参与进来。
notifyall:唤醒所有的线程。
下面为活生生列子一枚:
public class ThreadTest {
public static void main(String[] args) {
Account acc=new Account();
Custom c1=new Custom(acc);
Custom c2=new Custom(acc);
c1.setName("线程1");
c2.setName("线程2");
c1.start();
c2.start();
}
}
class Custom extends Thread{
Account ac;
public Custom(Account acc) {
this.ac=acc;
}
public void run(){
try {
for(int i=0;i<3;i++){
ac.deposit(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Account{
double balance;
public Account(){}
public synchronized void deposit(double many) throws InterruptedException{
notify();//唤醒线程
balance+=many;
Thread.currentThread().sleep(10);
System.out.println(Thread.currentThread().getName()+":"+balance);
wait();//挂起线程
}
}
打印结果 为交替执行:
线程1:1000.0
线程2:2000.0
线程1:3000.0
线程2:4000.0
线程1:5000.0
线程2:6000.0
相关文章推荐
- JAVA Socket 编程---Socket 和 ServerSocket
- springIDE
- 编写一个交错合并列表元素的函数。
- Struts2+Spring+Hibernate整合过程详解
- 【Java】基于ArrayList实现的简单登录注册
- Eclipse下使用Maven创建项目出现的archetype错误
- Java自定义注解及注解的使用
- spring-mvc.xml
- 【spring进阶】--控制反转(IoC)和依赖注入(DI)
- 从零开始写javaweb框架笔记6-需求分析与系统设计
- Java集合中HashMap的实现原理
- 在eclipse使用log4j记录日志
- Java.IO note
- 【Eclipse for IAR】使用 Eclipse 编写 IAR 程序
- 操作系统概念 管程Java代码实现
- java+struts+spring验证用户名是否存在
- Java数据库操作
- 今天 java第一课
- 今天来打打java大数模板(整型)
- 关于JavaWeb和mysql中文乱码的经验