java线程通信,解决线程之间的交互问题

来源:互联网 发布:json解析哪些框架 编辑:程序博客网 时间:2024/06/05 16:59

线程通信:

注意三个都是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

0 0
原创粉丝点击