java线程的通讯
⑴ java线程之间如何通信
volatile修饰的变量具有可见性。可见性也就是说一旦某个线程修改了该被volatile修饰的变量,它会保证修改的值会立即被更新到主存,当有其他线程需要读取时,可以立即获取修改之后的值。在Java中为了加快程序的运行效率,对一些变量的操作通常是在该线程的寄存器或是CPU缓存上进行的,之后才会同步到主存中,而加了volatile修饰符的变量则是直接读写主存。
volatile禁止指令重排 ,指令重排是指处理器为了提高程序运行效率,可能会对输入代码进行优化,它不保证各个语句的执行顺序同代码中的顺序一致,但是它会保证程序最终执行结果和代码顺序执行的结果是一致的。指令重排序不会影响单个线程的执行,但是会影响到线程并发执行的正确性。程序执行到volatile修饰变量的读操作或者写操作时,在其前面的操作肯定已经完成,且结果已经对后面的操作可见,在其后面的操作肯定还没有进行。
synchronized可作用于一段代码或方法,既可以保证可见性,又能够保证原子性。可见性体现在:通过synchronized或者Lock能保证同一时刻只有一个线程获取锁然后执行同步代码,并且在释放锁之前会将对变量的修改刷新到主存中。
原子性表现在:要么不执行,要么执行到底。从而我们可以看出volatile虽然具有可见性但是并不能保证原子性。
性能方面,synchronized关键字是防止多个线程同时执行一段代码,就会影响程序执行效率,而volatile关键字在某些情况下性能要优于synchronized。
但是要注意volatile关键字是无法替代synchronized关键字的,因为volatile关键字无法保证操作的原子性。
总结
⑵ 如何在学习Java过程中实现线程之间的通信
在java中,每个对象都有两个池,锁池(monitor)和等待池(waitset),每个对象又都有wait、notify、notifyAll方法,使用它们可以实现线程之间的通信,只是平时用的较少.
wait(): 使当前线程处于等待状态,直到另外的线程调用notify或notifyAll将它唤醒
notify(): 唤醒该对象监听的其中一个线程(规则取决于JVM厂商,FILO,FIFO,随机…)
notifyAll(): 唤醒该对象监听的所有线程
锁池: 假设T1线程已经拥有了某个对象(注意:不是类)的锁,而其它的线程想要调用该对象的synchronized方法(或者synchronized块),由于这些线程在进入对象的synchronized方法之前都需要先获得该对象的锁的拥有权,但是该对象的锁目前正被T1线程拥有,所以这些线程就进入了该对象的锁池中.
等待池: 假设T1线程调用了某个对象的wait()方法,T1线程就会释放该对象的锁(因为wait()方法必须出现在synchronized中,这样自然在执行wait()方法之前T1线程就已经拥有了该对象的锁),同时T1线程进入到了该对象的等待池中.如果有其它线程调用了相同对象的notifyAll()方法,那么处于该对象的等待池中的线程就会全部进入该对象的锁池中,从新争夺锁的拥有权.如果另外的一个线程调用了相同对象的notify()方法,那么仅仅有一个处于该对象的等待池中的线程(随机)会进入该对象的锁池.
java实现线程间通信的四种方式
1、synchronized同步:这种方式,本质上就是“共享内存”式的通信。多个线程需要访问同一个共享变量,谁拿到了锁(获得了访问权限),谁就可以执行。
2、while轮询:其实就是多线程同时执行,会牺牲部分CPU性能。
3、wait/notify机制
4、管道通信:管道流主要用来实现两个线程之间的二进制数据的传播
⑶ java线程间通信问题
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadDemo {
/**
* Semaphore 就是大学操作系统里面讲的信号量, 其方法acquire和release分别对应PV操作
* AtomicInteger 是原子变量,对它的操作会转化为底层的原语(不可分割的操作),这样多线程并发对其操作就不会有问题,
* 如果是普通的int就还要加锁才能保证没问题
*/
public static void main(String[] args) throws InterruptedException {
// 用于启动另一个线程
Semaphore startThread = new Semaphore(1);
// 用于控制终止程序
AtomicInteger threadCount = new AtomicInteger(0);
for (int i = 1; i <= 10; i++) {
CountThread t = new CountThread("Thread" + i, startThread,
threadCount);
t.start();
}
}
}
class CountThread extends Thread {
// 线程标识
private String label;
// 用于启动另一个线程
private Semaphore startThread;
// 用于控制终止程序
private AtomicInteger threadCount;
public CountThread(String label, Semaphore startThread,
AtomicInteger threadCount) {
this.label = label;
this.startThread = startThread;
this.threadCount = threadCount;
}
public void run() {
try {
// 等待线程被唤醒
startThread.acquire();
System.out.println("------线程:" + label + " 开始工作------");
} catch (InterruptedException e) {
e.printStackTrace();
}
int num = 0;
while (true) {
System.out.println("线程:" + label + "计数:" + num);
// 计数到5
if (num++ == 5) {
// 唤醒另一个计数线程
startThread.release();
// 10的时候程序终止, incrementAndGet是递增(也就是++操作), 再取值
if (threadCount.incrementAndGet() == 10) {
System.exit(1);
}
}
}
}
}
研究Java并发,强烈推荐你看《Java并发编程实践》
⑷ Java 中利用管道实现线程间的通讯
在Java 语言中 提供了各种各样的输入输出流(stream) 使我们能够很方便的对数据进行操作 其中 管道(pipe)流是一种特殊的流 用于在不同线程(threads)间直接传送数据 一个线程发送数据到输出管道 另一个线程从输入管道中读数据 通过使用管道 实现不同线程间的通讯 无需求助于类似临时文件之类的东西 本文在简要介绍管道的基本概念后 将以一个具体的实例pipeapp加以详细说明 .管道的创建与使用Java提供了两个特殊的专门的类专门用于处理管道 它们就是pipedinputstream类和pipeoutputstream类 Pipedinputstream代表了数据在管道中的输出端 也就是线程向管道读数据的一端 pipeoutputstream代表了数据在管道中的输入端 也就是线程向管道写数据的一端 这两个类一起使用可以提供数据的管道流 为了创建一个管道流 我们必须首先创建一个pipeoutstream对象 然后 创建pipeinputstream对象 实例如下 pipeout= new pipedyoutstream();pipein= new pipedputsteam(pipepout);一旦创建了一个管道后 就可以象操作文件一样对管道进行数据的读写 .演示程序 pipeapp应用程序由三个程序组成 主线程(pipeapp Java)及由主线程启动的两个二级线程(ythread Java和zthread Java) 它们使用管道来处理数据 程序从一个内容为一行一行 x 字母的 input txt 文件中读取数据 使用管道传输数据 第一次是利用线程ythread将数据 x 转换为 y 最后利用线程zthread将 y 转换为 z 之后 程序在屏幕上显示修改后的数据 主线程 (pipeapp Java)在main()方法中 程序首先创建一个应用对象 pipeapp pipeapp=new pipeapp();由于程序中流操作都需要使用IOException异常处理 所以设置了一个try块 在try中 为了从源文件中读取数据 程序为 input txt 文件创建了一个输入流Xfileln :fileinputstream xfileln= new fileinputstream( input txt );新的输入流传递给changetoy()方法 让线程ythread能读取该文件 inputstream ylnpipe =pipeapp changetoy(xfileln);changetoy()方法创建将输入数据 x 改变到 y 的线程ythread 并返回该线程的输入管道 inputstream zlnpipe = pipeapp changetoz(ylnpipe);changetoz()方法启动将数据从 y 改变到 z 的线程zehread 主程序将使用从changetoz()返回的输入管道 得到以修改的数据 然后 程序将管道输入流定位到datainputstream对象 使程序能够使用readline()方法读取数据 datainputstream inputstream = new datainputstream(zlnpiepe);创建了输入流以后 程序就可以以行一行的读取数据病显示在屏幕上 String str= inputstream readline();While(str!=null){system out println(str);str=inputstream readline();} 显示完成之后 程序关闭输入流 inputstream close();changetoy()方法 changetoy()方法首先通过传递一个参数inputstream给datainputstream对象来定位资源的输入流 使程序能使用readline()方法从流中读取数据 datainputstream xfileln =new datainutstream(inputstream) 然后 changetoy()创建输出管道和输入管道 pipeoutstream pipeout = new pipeoutputstream();pipeinputstream pipeln = new pipedinputsteam(pipeout); 为了能够使用println()方法输出修改的后的文本行到管道 程序将输出管道定位到printstream对象 printstream printstream = new printstream(pipeout);现在 程序可以创建将数据从x改变到y的线程 该线程是ythread类的一个对象 他传递两个参数 输入文件(xfileln)和输出管道(调用printstream)ythread ythread =new thread(xfileln printstream);之后 程序启动线程 changetoz()方法changetoz()方法与changetoy()方法很相似 他从changetoy()返回的输入流开始 datainputstream yfileln= new datainputstream(inputstream);程序创建一个新的管道 pipedoutstream pipeout = new pipedoutputstream();pipedinputstream pipeln = new pipedinputsream(pipeout ); 该线程通过这个新的管道发出修改后的数据(输入流pipeln )给主程序 源程序如下 ////pipeapp Java pipeapp的主应用程序//import Java io *class pipeapp{public static void main(string[] args){pipeapp pipeapp=new pipeapp();try{fileinputstream xfile =new fileinputstream( input txt );inputstream ylnpipe = pipeapp changetoy(xfileln);inputstream zlnpipe=pipeapp changetoz(ylnpipe);system out println();system out println( here are the results );system out pringln();datainputstream inputstream = nes datainputstream(zlnpipe);string str = inputstream readline();while (str!=null){system out println(str);str=inputstream readline();}inputstream close();}catch(exception e){system out println(e tostring());}}public inputstream changetoy(inputstream inputstream){try{datainputstream pipeout = new datainputsteam(inputstream);pipedoutstream pipeout = new pipedoutputstream();pipedlnsteam pipeln = new pipedlnputstream(pipeout);printstream printstream = new printstream(pipeout);ythread ythread = new ythread(xfileln printstream);ythread start();return pipeln;}catch(exeption e){system out println(x tostring());}return null;}public inputstream changetoz(inputstream inputsteam){try{datainputstream yfileln = new datainputstream(inputstream);pipeoutputstream pipeln = new pipedinputstream(pipeout );printrstream printstream = new printsteam(pipeout );zthread zthread = new zthread(yfileln printstream );zthread start();return pipeln ;}catch(exception e){system out println(e tostring());}return null;}} Ythread类和Zthread类由于ythread类与zthread类基本一样 在此仅以ythread为例加以说明 Ythread的构造器接收两个参数 输入的文件和第一个管道的输出端 构造器存储这两个参数作为类的数据成员 Ythread(datainputstream xfileln pringstream printstream){this xfileln = xfileln;this printstream = printstream;} 线程通过run()方法来处理数据 首先读取一行数据 确保xstring不为空的情况下循环执行 string xstring = xfileln readline();每读一行数据 完成一次转换string ystring = xstring replace( x y );然后将修改后的数据输出到管道的输出端 prinstream prinrln(ystring);为了确保所有缓冲区的数据完全进入管道的输出端 pringstram flush();循环完成后 线程关闭管道输出流 pringstram close();ythread类的源程序如下 //ythread Java//import Java io *;class ythread exteads thread{datainputstream xfileln;pringstream printstream;ythread(datainputstream xfileln pringstream printstream){this xfileln = xfileln;this printstream = printstream;}public void run(){try{string xstring = xfileln readline();while(xstring!=null){string ystring= xstring replace( x y );printstream pringln(ystring);printstream flush();xstring= xfileln readline();}printstream close();}catch{ioexception e}{system out println(e tostring());}}} pipeapp应用程序使用microsoft visual j++ 编译 lishixin/Article/program/Java/gj/201311/27508