线程协作
多线程之间具有相互的同步关系,比如:券商和用户
券商为用户提供服务,有了冲突谁错谁让步,这样使一个协调的合作关系;
Java中的编程协调合作:
把我们的对象继承多线程实例化分工协作,冲突用一下方法协调
构造方法:
wait() 停止执行当前线程—阻塞态
notify() 使当前处于第一个阻塞态的线程运行
notifyAll() 使当前处于所以阻塞态的线程运行
使用注意:
wait()方法要在synchronized方法中使用
notify() 和notifyAll()也要在synchronized方法中使用
我们在编码的时候要注意逻辑思维,把实际中的过程一步步理清,然后通过代码实现.
常用案例展示:吃汉堡比赛
public class S2 {
public static void main(String[] args) {
new Shengchan().start();
new Xiaofizhe().start();
}
}
//_______________________________________________________
public class Shengchan extends Thread{
public static List<Integer> l= new ArrayList<Integer>();
public static int i;
@Override
public void run() {
while (true){
//当汉堡小于十个的时候,往容器里面加入汉堡
if (l.size()<10){
l.add(i);
System.out.println("生产汉堡"+i);
i++;
//同时汉堡小于10个通知厨师制作汉堡
synchronized(l){
l.notifyAll();
}
//汉堡等于10个停止制作
}else {
try {
l.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//报异常直接try catch掉
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//___________________________________________________________
public class Xiaofizhe extends Thread{
//消费者是消灭容器里面的面包,所以对集合进行删减操作就可实现
//run方法中实现
@Override
public void run() {
while (true){
//容器里面的数量大于0吃汉堡
if (Shengchan.l.size()>0){
Integer r = Shengchan.l.remove(0);
System.out.println("消灭汉堡"+r);
//同时提示消费者吃汉堡
synchronized (Shengchan.l){
Shengchan.l.notifyAll();
}
//当容器汉堡等于0的时候停止吃,让厨师感觉做
}else {
synchronized (Shengchan.l){
try {
Shengchan.l.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}