线程的通信

线程的通信
不同的线程执行不同的工作 如果这些工作有某种关系,线程之间必须能够通信,协调完成工作

经典例子 生产者和消费者的案例
分析:
1.)生产者和消费者应该操作共享的资源(实现方式来做)
2.)使用一个或者多个线程来表示生产者(prouduce)
3.)使用一个或者多个线程来表示消费者(consumer)

生产者将生产的资源存入共享资源 消费者再从共享资源中取出资源 体现了面向对象的设计理念:低耦合

同步锁机制 使用
waite 释放锁
notify 唤醒线程
package cn.bdqn.manytread;

public class Consumer implements Runnable {

private ShareResource resource = null;

public Consumer(ShareResource resource) {
    super();
    this.resource = resource;
}

@Override
public void run() {
    // TODO Auto-generated method stub
    for (int i = 0; i < 30; i++) {
        resource.popup();   
    }

}

}
package cn.bdqn.train526;

/*class TestDemo {
String i;

public TestDemo() {
    System.out.println(i);
}

}
*/
class ShareResource {
private String name;
private String gender;
boolean isEmpty=true;//表示共享资源是否为空

/**
 * 生产者向共享资源中存储数据
 * @param name 名字
 * @param gender 性别
 */
synchronized public  void push(String name, String gender) {
    try{
    while(!isEmpty)
    {
        this.wait();
    }
    //生产
    this.name = name;
    this.gender = gender;
    isEmpty=false;
    this.notifyAll();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    //System.out.println(this.name + "    " + this.gender);
}

/**
 * 消费者去除数据
 */
synchronized public void popup() {
    try {
        while(isEmpty)
        {
            this.wait();
        }
        System.out.println(this.name + "    " + this.gender);
        isEmpty=true;
        this.notifyAll();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

}

}

/**
* 生产者
* @author ASUS
*
*/
class Proudecer implements Runnable {

private ShareResource resource = null;

public Proudecer(ShareResource resource) {
    super();
    this.resource = resource;
}

@Override
public void run() {
    // TODO Auto-generated method stub
    for (int i = 0; i < 30; i++) {
        if (i % 2 == 0) {
            resource.push("嘿嘿", "女");
        } else {
            resource.push("哈哈", "男");
        }
    }
}

}

public class Test {

public static void main(String[] args) {
    ShareResource re = new ShareResource();
    //启动生产者线程
    new Thread(new Proudecer(re)).start();
    //启动消费者线程
    new Thread(new Consumer(re)).start();

}

}

lock机制使用condition接口
await取代wait
singal singlAll 取代notify

package cn.bdqn.manytread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*class TestDemo {
String i;

public TestDemo() {
    System.out.println(i);
}

}
*/
class ShareResource {
private String name;
private String gender;
boolean isEmpty=true;//表示共享资源是否为空
private final Lock lock=new ReentrantLock();
private Condition condition=lock.newCondition();
/**
* 生产者向共享资源中存储数据
* @param name 名字
* @param gender 性别
*/
public void push(String name, String gender) {
lock.lock();// 锁机制

    try{
        while(!isEmpty)
        {
            condition.await();
        }

    //生产
    this.name = name;
    this.gender = gender;
    isEmpty=false;
    condition.signalAll();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        lock.unlock();
    }
    //System.out.println(this.name + "    " + this.gender);
}

/**
 * 消费者去除数据
 */
 public void popup() {
    lock.lock();
    try {

        while(isEmpty)
        {
            condition.await();
        }

        System.out.println(this.name + "    " + this.gender);
        isEmpty=true;
        condition.signalAll();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }finally
    {
        lock.unlock();
    }

}

}

/**
* 生产者
* @author ASUS
*
*/
class Proudecer implements Runnable {

private ShareResource resource = null;

public Proudecer(ShareResource resource) {
    super();
    this.resource = resource;
}

@Override
public void run() {
    // TODO Auto-generated method stub
    for (int i = 0; i < 30; i++) {
        if (i % 2 == 0) {
            resource.push("嘿嘿", "女");
        } else {
            resource.push("哈哈", "男");
        }
    }
}

}

public class Test {

public static void main(String[] args) {
    ShareResource re = new ShareResource();
    //启动生产者线程
    new Thread(new Proudecer(re)).start();
    //启动消费者线程
    new Thread(new Consumer(re)).start();

}

}

多线程通信的时候很容易造成死锁,死锁无法解决自能避免
当A线程等待B线程持有的锁,而B线程等待A线程持有的锁时,发生死锁现象虚拟机不检测不处理这种现象
避免法则:当多个资源都要访问共享的A B C时 保证每一个线程按照相同的顺序去访问他们 ABC
Thread.suspend挂起线程 resume 使暂停的线程恢复
容易造成死锁现象

/********************************
线程的生命周期
线程生命周期中的状态 以及状态相互之间的转换
6个状态或者5种
新建(state) 可运行runnable 等待waiting 计时等待timewait 终止terminated 阻塞blocked
在给定的时间点上 一个线程只能有一个状态
1.新建状态new:仅仅只是存在一个线程对象 并没有启动 Thread t=new Thread();
2.可运行状态:当新建的线程调用start();只能调用一次
runnable 分两种状态 ready(就绪) runing(运行)

3.阻塞状态blocked:正在运行的线程 放弃CPU暂时停止运行,知道线程进入就绪状态

两种情况 1.试图获取同步锁未果时 存在锁池中
2.当线程处于运行过程中有IO请求的时候比如System.in.read 接收一个键盘的输入

4.等待状态 waiting 只能被其他线程唤醒
1调用wait()方法时
5.计时等待
使用 waite(100)方法
使用sleep(100)方法

6 .终止状态
a 正常执行完程序
b.遇到异常之后程序中断 一旦终止便不能在重启
Thread.isAlive

线程睡眠
让运行的线程暂停一段时间 在这段时间内 不会获得执行的机会 但是不会释放同步锁 同步监听器
该方法用于模拟网络延迟的 让多线程访问同一个资源的错误效果更明显

线程联合 ()join方法 联合线程
join方法 表示一个线程等待另一个线程执行完后才执行

后台线程 在后台运行的线程 为前台的线程提供服务的 比如垃圾回收器 所有的前台线程肆万 后台线程自动死亡
setDaemon(true) 设置为后台线程 isDaemon获取当前线程是否为后台线程 父线程为啥线程子线程就为啥线程 设置后台线程必须在新建状态

/*
线程的优先级: 优先级的高低只与线程的执行机会的次数多少有关 与先后顺序无关
getPriority() set 设置获取线程的优先级 先启动后设置 1到10

线程礼让:
yield() 暂停当前的线程 让其他线程执行 但调度器可以忽略该提示
调用该方法之后 当前线程进入就绪状态 只能将机会让给优先级更高的线程

定时器 和线程组

java.util

timer

线程组:
多个线程放一起 ThreadGroup

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值