您的位置:首页 > 编程语言 > Java开发

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: