关于线程通信
使用多线程编程的一个重要原因就是线程间通信的代价比较小
--如果朋友您想转载本文章请注明转载地址"http://www.cnblogs.com/XHJT/p/3897773.html "谢谢--
关键技术:
yield(): Thread类的一个静态方法,用来暂停当前正在执行的线程对象,并执行其他线程
public static void yield(){}
代码实例:
实现线程间的发送和接收消息
package com.xhj.thread; /** * 线程之间的通信 Thread.yeild()暂停当前线程,执行其他线程 * * @author XIEHEJUN * */ public class CommunicationThread { /** * 发送线程类 * * @author XIEHEJUN * */ private class SendThread implements Runnable { private String[] products = { "java宝典", "C#宝典", "C宝典", "C++宝典", "Pyhtion宝典" }; private volatile String productName; private volatile boolean sendState; public String getProductName() { return productName; } public void setSendState(boolean sendState) { this.sendState = sendState; } public boolean isSendState() { return sendState; } @Override public void run() { for (int i = 0; i < 5; i++) { while (sendState) { Thread.yield(); } productName = products[i]; System.out.println("发送:" + productName); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } sendState = true; } } } /** * 接受线程类 * * @author XIEHEJUN * */ private class ReceiveThrend implements Runnable { private SendThread send; public ReceiveThrend(SendThread send) { this.send = send; } @Override public void run() { for (int i = 0; i < 5; i++) { while (!send.isSendState()) { Thread.yield(); } System.out.println("接收:" + send.getProductName()); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } send.setSendState(false); } } } /** * 调用线程 */ public void useThread() { SendThread send = new SendThread(); ReceiveThrend receive = new ReceiveThrend(send); System.out.println("线程1"); Thread thread1 = new Thread(send); thread1.start(); System.out.println("线程2"); Thread thread2 = new Thread(receive); thread2.start(); } public static void main(String[] args) { // TODO Auto-generated method stub CommunicationThread communicationThread = new CommunicationThread(); communicationThread.useThread(); } }
注:线程间的通信重点关注通信的内容,要确保其是同步的,而且各个线程对该资源使用后是要及时释放的,
否则将会出现死锁现象。而且在实际应用当中,商品的信息通常都是存储在数据库中的。
java笔记--关于线程通信
时间: 2024-11-03 03:04:48