android线程间通信

public void wait()导致当前线程等待,直到另一个线程调用notify()。
public void notify()唤醒正在此对象监视器上等待的单个线程。
public void notifyAll()唤醒在同一对象上调用wait()的所有线程。

1.启动线程

public class OneActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cabinet_type_1);

        Chat m = new Chat();
        new T1(m);
        new T2(m);
    }
}

2.启动两个线程 执行不同的任务


public class Chat {
    boolean flag = false;

    //被synchronized 修饰的方法 同一时间只能被一个线程使用
    public synchronized void Question(String msg) {
        if (flag) {
            try {
                wait();  //线程等待,直到另一个线程调用notify()
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Log.e("TAG", msg);
        flag = true;
        notify();  //唤醒正在此对象监视器上等待的单个线程
    }

    public synchronized void Answer(String msg) {
        if (!flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Log.e("TAG", msg);
        flag = false;
        notify();
    }
}

3.线程1:

public class T1 implements Runnable {
    Chat m;
    String[] s1 = {"Thread1-Hi", "Thread1-How are you ?", "Thread1-I am also doing fine!"};

    public T1(Chat m1) {
        this.m = m1;
        new Thread(this, "Question").start();
    }

    @Override
    public void run() {
        for (int i = 0; i < s1.length; i++) {
            m.Question(s1[i]);
        }
    }
}

4.线程2:

public class T2 implements Runnable {
    Chat m;
    String[] s2 = {"Thread2-Hi", "Thread2-I am good, what about you?", "Thread2-Great!"};

    public T2(Chat m2) {
        this.m = m2;
        new Thread(this, "Answer").start();
    }

    @Override
    public void run() {
        for (int i = 0; i < s2.length; i++) {
            m.Answer(s2[i]);
        }
    }
}

运行结果:

05-16 18:28:59.705 19418-19438/? E/TAG: Thread1-Hi
05-16 18:28:59.705 19418-19439/? E/TAG: Thread2-Hi
05-16 18:28:59.705 19418-19438/? E/TAG: Thread1-How are you ?
05-16 18:28:59.705 19418-19439/? E/TAG: Thread2-I am good, what about you?
05-16 18:28:59.705 19418-19438/? E/TAG: Thread1-I am also doing fine!
05-16 18:28:59.705 19418-19439/? E/TAG: Thread2-Great!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值