Java SE 多线程 线程通信
package thread;
class QQ{
private String name;
private String sex;
boolean flag=false;
public synchronized void put(String name,String sex){
if(flag)
try {
wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
this.name=name;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.sex=sex;
flag=true;
notify();
}
public synchronized void get(){
if(!flag)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name +"----------->"+sex);
flag=false;
notify();
}
}
class Producer1 implements Runnable{
QQ qq=null;
public Producer1(QQ qq){
this.qq=qq;
}
public void run() {
int i=0;
while(true){
if(i==0){
qq.put("zxx", "nan");
}else{
qq.put("cq", "nv");
}
i=(i+1)%2;
}
}
}
class Consumer1 implements Runnable{
QQ qq=null;
public Consumer1(QQ qq){
this.qq=qq;
}
public void run() {
while(true){
qq.get();
}
}
}
public class ThreadCommunciation {
public static void main(String[] args) {
QQ qq=new QQ();
new Thread(new Producer1(qq )).start();
new Thread(new Consumer1(qq)).start();
}
}
相关文档:
package org.mingyuan.fetcher;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
i ......
文中引用了孙老师的代码,并注明。
import java.io.*;
import java.net.*;
public class EchoServer {
private int port=8888;
private ServerSocket serverSocket;
public EchoServer() throws IOException {
serverSocket = new ServerSocket(port);
System.out.println("服务器启动");
......
下面开讲故事:
从前有个房间,房间里有份文档,房间还有一把钥匙。 这把钥匙在张三手里。
这时李四来向张三要那份文档。 张三不太喜欢李四,但又怕耽误了
工作不好交代。于是张三就把房间里文档的文档复印了一份,然后把那个复印件交给了李四(这叫传值)。
李四拿到文档后(复印件),胡乱修改一 ......
E:\>javac -X
-Xlint 启用建议的警告
-Xlint:{all,deprecation,unchecked,fallthrough,path,serial,finally,-deprecat ion
,-unchecked,-fallthrough,-path,-serial,-finally}启用或禁用特定的警告
& ......
package demo;
class TestA{
public int devide(int x,int y) throws ArithmeticException , DevideByMinusException{
if(y<0)
throw new DevideByMinusException("被除数为负",y);
int result=x/y;
return result;
}
}
public class TestE ......