[java]线程(二)

2014-11-24 09:09:53 · 作者: · 浏览: 6
d t1 = new Thread(send);
Thread t2 = new Thread(rec);
t1.start();
t2.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}

class PipedSend implements Runnable {
OutputStream out;

public PipedSend(OutputStream out) {
this.out = out;
}

@Override
public void run() {
for (int i = 1; i <= 5; i++) {
byte theva lue = (byte) new Random().nextInt(256);
try {
out.write(theva lue);
System.out.println("send the value is:" + theva lue);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

class PipedRec implements Runnable {
InputStream in;

public PipedRec(InputStream in) {
this.in = in;
}

@Override
public void run() {
for (int i = 1; i <= 5; i++) {
try {
byte theva lue = (byte) in.read();
System.out.println("receive the value is:" + theva lue);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

}
/**
* 运行结果是:
* send the value is:61
* send the value is:17
* send the value is:63
* send the value is:-81
* send the value is:94
* receive the value is:61
* receive the value is:17
* receive the value is:63
* receive the value is:-81
* receive the value is:94
*/


---生产者和消费者---用yeild方法处理---不叫耗资源、安全性低


[java]
package guo;

import java.util.Random;

public class Demo11 {
public static void main(String[] args) {
FlagSend send = new FlagSend();
FlagRec rec = new FlagRec(send);
Thread t1 = new Thread(send);
Thread t2 = new Thread(rec);
t2.setDaemon(true);
t1.start();
t2.start();

}
}
//生产者
class FlagSend implements Runnable{
boolean flag;
int theva lue;
@Override
public void run() {
for(int i = 0; i < 5;i++){
while(flag){
Thread.yield();
}
theva lue = new Random().nextInt(1000);
flag = true;
System.out.println("send the value is:"+theva lue);
}
}
}
//消费者---->把生产的对象作为自己的成员
class FlagRec implements Runnable{
FlagSend send;
public FlagRec(FlagSend send){
this.send = send;
}
@Override
public void run() {
while(true){//死循环
while(!send.flag){
Thread.yield();
}
System.out.println("receiver the value is:"+send.theva lue);
send.flag = false;
}
}

}


---wait notify来交互

这两个方法不是线程的方法,是Object类的方法,每个对象上都可以拥有一个线程等待池,挂在这个对象 上的线程,就可以通过这个对象去让线程等待和唤醒,wait和notify必须放在同步块中


[java]
package guo;

import java.util.Random;

public class WaitTest {
public static void main(String[] args) {
WaitSend send = new WaitSend();
WaitRec rec = new WaitRec(send);
Thread t1 = new Thread(send);
Thread t2 = new Thread(rec);
t2.setDaemon(true);
t1.start();
t2.start();
}
}
//生产者
class WaitSend implements Runnable{
boolean flag;
int theva lue;
@Override
public void run() {
for(in