`
skycity220
  • 浏览: 18245 次
  • 性别: Icon_minigender_1
  • 来自: 广州
文章分类
社区版块
存档分类
最新评论

JAVA学习io,net,线程

阅读更多
方法覆盖复习:修饰符(相同或更宽),返回值(相同或是父类返回类型的子类型),方法
名相同,参数列表相同,抛出的异常(不能抛出比父类方法更多的异常)
反射: java.lang.Class
        java.lang.reflect.Field
        java.lang.reflect.Method
        java.lang.reflect.Constructor
        java.lang.reflect.Array
//                   1.得到类对象
                     Class c = Class.forName("Student");
//                   2.通过类对象产生对象(调用无参的构造方法)
                     //Object obj = c.newInstance();
                     2.a 通过类对象找到相应的Constructor对象
//
                     Constructor cons =c.getConstructor(String.class,int.class);
                     2.b 通过Constructor对象得到对象
//
                     Object obj = cons.newInstance("zhangsan",20);
                     System.out.println(obj);
//                   3.通过类对象找到相应的Method对象
                     Method m1 = c.getDeclaredMethod("getAge");
//                   4.调用对象的方法。
                     Object age = m1.invoke(obj);
                     System.out.println(age);
                     Method m2 = c.getDeclaredMethod("study", String.class);
                     m2.invoke(obj, "corejava");
标注:
@Override   标注     给编译器看
@SuppressWarnings("unused")
@SuppressWarnings("unchecked")
@Deprecated过时,不推荐使用。。不删除是为了向后兼容
定义自己的标注:
  public @interface 标注名称{
           类型    属性()        default    默认值;
}
元数据:数据的数据
元标注:标注的标注
@Author(@Name(first=”Tony”,last=”Tan”))
标注属性类型 只能是8种基本类型,String.枚举类型,Class,注释标注类型,对应的一维
数组
import java.lang.annotation.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
@Retention(value=RUNTIME)//这样设置才能使用反射方式探查出来
@Target(value=)
public @interface Test {
                    String value()   default "No Parameter";
}
1定义注释:MyTest         String author String date
import java.lang.annotation.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.METHOD;
@Retention(value=RUNTIME)
@Target(value=)
public @interface MyTest {
                    String author() default "itemMgr";
                    String date() default "2009-2-16";
}
2写一个类,使用MyTest注释                @MyTest(author="itemMgr",date="2009-2-10")
3通过反射调用某人写的方法;
          Class c = Class.forName("Util");
          Object obj = c.newInstance();
          //得到所有方法
          Method[] mm = c.getDeclaredMethods();
          for(Method m:mm){
          //判断方法是否有Test注释
          boolean b = m.isAnnotationPresent(Test.class);
          if(b){
           //得到注释
          Test t = m.getAnnotation(Test.class);
          //通过注释得到注释中的属性
          String param = t.value();
          //调用方法
          m.invoke(obj, param);
                                         }
这里实现了类似Junit的测试框架。当标注为test before after 等等,会相应调用方法
来测试类
线程:宏观上并行,微观上串行
第一种方式:extends Thread 继承   覆盖run()方法 .start()启动一个线程
currentThread() 当前线程
优先级只是一个参考。不要使用优先级来控制线程
第二种 方法:implements Runnable接口。实现run()方法
Thread(Runnable)
eclipse常用快捷键:
syso main   Alt+/ 主方法,打印语句
ctrl+1  错误提示操作
ctrl+/ 注释
ctrl+d删一行
ctrl+-> <- 切换编辑工作区
加载配置文件:java.util.Properties
          .load(InputStream)
          .getProperty(String key)
反射:
          File[] fs = cz.getDeclaredFields();
          for(Field f:fs){//得到属性名字          根据完全封装规范转换得到 get/set 方法名:
                     String attributeName = f.getName();
                       char c = attributeName.charAt(0);//获得属性第一个字母
                     c -= 32; //转成大写
          String mn = “set”+c+attributeName.substring(1);//构造 get/set 方法名
          }
线程三要素:cpu data ,code
产生线程的方式:a             extends Thread   覆盖 run 方法调用 Thread 的 start()
                  b    implements Runnable 接口,实现 run()方法
                     new Thread(runImpl) .start();
Thread.sleep()进入休眠
Thread.currentThread()当前执行线程
中断:work(){
          while(true){
                     if(flag == false){
                                throw new InterruptedException()
                     }
                     run
          }
}
try{
work()
}cathc(IterruptedException){}
同步代码块
public void run(){
while(tickets > 1){
synchronized(obj){
if(tickets<=1) break;
tickets --;
System.out.println(Thread.currentThread()+" : "+tickets);
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}}}}
synchronized 修饰方法 代码块
// synchronized 修饰静态方法,锁对象是类对象
会造成死锁
新特性:java.util.concurrent.locks
接口 Lock
    public void m() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }
java.util.concurrent.atomic 原子操作
volatile 只能修饰实例变量。同步范围仅仅是变量级的
volatile boolean flag = false;
while(true){
             if(falg){
                        throws new InterruptedException()
             }
             work();
}
public void start(){
             flag = false;
}
public void cancel(){
             flag = true;
}
notify() notiyfAll() wait() 在 synchonized()代码中。
  synchronized(this){
  try {
notifyAll();
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.yield();//?该方法不一定能调用成功暂停当前正在执行的线程对象,并执行其他线程。其
它线程可能是当前线程
高级特性
executor 接口执行已提交的 Runnable 任务的对象。此接口提供一种将任务提交与每个任务将如何运行
的机制(包括线程使用的细节、调度等)分离开来的方法。通常使用 Executor 而不是显式地创建线程。例
如,可能会使用以下方法,而不是为一组任务中的每个任务调用 new
Thread(new(RunnableTask())).start():
  Executor executor = anExecutor;
  executor.execute(new RunnableTask1());
  executor.execute(new RunnableTask2());
接口回调: 调用接口中的方法实际上调用的是实现者的方法
线程池           ExecutorService
ExecutorService exec =Executors.newFixedThreadPool(2);
exec.submit(new ThreadA());
exec.submit(new ThreadB());
exec.shutdown();
Callable Future
1线程,三要素
2.如何产生线程
3synchronized
4wait.notify
Lock ReadWriteLock -> synchronzied
Executor/ExecutorService -> Thread
Callable/Future -> Runnable
Condition.await -> wait
Condition.signal ->notify
Io流      File
File f = new File("a.txt");
System.out.println(f.exists());//判断一文件是否存在
if(!f.exists()){
boolean b = f.createNewFile();//创建文件
System.out.println(b);
}
System.out.println(f.delete());//删除文件,成功 true
System.out.println(f.getAbsolutePath());//获得绝对路径
System.out.println(f.getPath());
System.out.println(File.separator);
System.out.println(f.isFile());
System.out.println(f.isDirectory());
System.out.println(f.isAbsolute());
//创建目录
File f = new File("dir");
System.out.println(f.mkdir());
针对FileFilter接口编程。(当接口没有给出实现时,都是需要用户自己实现接口或者用
匿名内部类)
class MyFilter implements FileFilter{
            public boolean accept(File pathname) {
                      String name = pathname.getName().trim();
                      if(name.endsWith(".txt"))
                      return true;
                      return false;}}
Input Stream & Output Stream
Byte Stream & Char Stream
Node Stream & Wrapper Stream
InputStream    读入 read()     读一个字节
read(byte[] b) b 是一个缓冲
byte[] buf = new byte[5];
while(true){
int len =in.read(buf,1,3);
if(len == -1) break;
System.out.println(len);
System.out.println(Arrays.toString(buf));
}
in.close();
OutputStream     写入write() 写入一个字节
包装流: DataInputStream DataOutputStream         中有一次性写读Int ,Short,Long.Double
等包装类型
            BufferedOutputStream BufferedInputStream 记得写入时要flush
byte[] b = new byte[100];一次性读 100 个字节
int len = 0;//是否读到文件末尾。。注意                          in = read(byte[])方法
while((len=in.read(b))!=-1){
}
in.close();


PipedOutputStream pout       = new PipedOutputStream();
PipedInputStream pin = new PipedInputStream();      连接管道流
pout.connect(pin);
ObjectInputStream & ObjectOutputStream 对象流
Serizlizable序列化接口。。可将一个对象写入文件或在网络上传输
序列化文件以 ACED 开头
序列化可以给一个对象加上标识(序列号)                          当修改对象类时,只要序列号一样,在文件
和网络上就能找到该对象。
transient    表此属性不序列,是一个临时属性                     8 大基本类型都实现了序列化接口
在序列化类中有引用类型,也需要保存时都要序列化
Serialiver 命令,可查看序列化                序列化不可在后面追加。因为在一个文件中 ACED 只能
出现一次
要追加只好读出来再追加后写进去
字节流完
字符流:Reader         Writer
        InputStreamReader      包装类,包装字节流 桥转换:字节流转换成字符流
     桥转换过程中可设定编码
           BufferedReader readLine()
           PrintWriter
           StringReader
           FileReader 直接读文件,不用桥转换
           BufferedWriter
           RandomAccessFile 随机访问文件
System.setOut(new PrintStream("a.txt"));//不输出在控制台,而输出到文件
System.out.println("Hello World");
System.out.println(System.out.getClass());
//InputStream in = System.in;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
String s = br.readLine();
if(s.equals("exit")) break;
System.out.println(s);
}
JAVA图形界面
JFC Swing   AWT事件处理
Creating GUI    1:choosing A Container
          (JFrame Jdialog,JApplent,JPanel) JtabbedPane
               2:choosing A layout Manager
               3:Adding Components in the Containter
               4:Creating Event Handlers
事件监听原理:
import java.util.*;
public class TestGirl {
public static void main(String[] args) {
Girl g = new Girl("秋香");
Boy1 boy1 = new Boy1("xiegy");
g.addEmotionListener(boy1);
Boy2 boy2 = new Boy2("zhaojun");
g.addEmotionListener(boy2);
g.fire();
}
}
interface EmotionListener {
void whatCanIDoWhenGirlHappy(EmotionEvent e);
void whatCanIDoWhenGirlSad(EmotionEvent e);
}
//
////事件对象封装事件源
//class EmotionEvent{
// private Object source;//事件源
// public EmotionEvent(Object source){
// this.source = source;
// }
// public Object getSource() {
// return source;
// }
//
//}
//事件对象封装事件源
class EmotionEvent extends EventObject{
public EmotionEvent(Object source) {
super(source);
}
}
//事件源
class Girl {
private String name;
private List<EmotionListener> listeners = new
ArrayList<EmotionListener>();
public void addEmotionListener(EmotionListener listener){
listeners.add(listener);
}
public void removeEmotionListener(EmotionListener listener){
listeners.remove(listener);
}
public void fire(){
for(int i=1;i<=5;i++){
System.out.println("Day"+i);
if(i%2 == 0){
System.out.println(name+"说:今天
心情不好!");
for(EmotionListener e:listeners){
//所谓事件源向监听者发
出消息,即通过事件对象封装事件源
//然后以事件对象为参数
调用监听者的相应方法
EmotionEvent event =
new EmotionEvent(this);
e.whatCanIDoWhenGirlSad(event);
}
}else{
System.out.println(name+"说:今天
天气好,心情好!");
for(EmotionListener e:listeners){
EmotionEvent event =
new EmotionEvent(this);
e.whatCanIDoWhenGirlHappy(event);
}
}
}
}
public Girl(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
//事件处理者
class Boy1 implements EmotionListener {
private String name;
public Boy1(String name) {
this.name = name;
}
@Override
public void whatCanIDoWhenGirlHappy(EmotionEvent e) {
Girl g = (Girl)e.getSource();
System.out.println(name + "对"+g.getName()+"说:你开心我也挺开
心!");
}
@Override
public void whatCanIDoWhenGirlSad(EmotionEvent e) {
Girl g = (Girl)e.getSource();
System.out.println(name + "对"+g.getName()+"说:你EmotionEvent不
开心我也不开心!");
}
}
class Boy2 implements EmotionListener {
private String name;
public Boy2(String name) {
this.name = name;
}
@Override
public void whatCanIDoWhenGirlHappy(EmotionEvent e) {
Girl g = (Girl)e.getSource();
System.out.println(name + "对"+g.getName()+"说:你开心我倒不开
心!");
}
@Override
public void whatCanIDoWhenGirlSad(EmotionEvent e) {
Girl g = (Girl)e.getSource();
System.out.println(name + "对"+g.getName()+"说:你不开心我也开
心!");
}
}
private class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
jta.append(jtf.getText()+”\n”);
jtf.setText();
}
}
private class MyKeyListener extends KeyAdapter{
@Override
public void KeyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ENTER){
jta.append(jtf.getText()+”\n”);
jtf.setText();
}
}
Java net 网络编程
端口0~65535
0~1024系统保留端口
IPV4 192.168.0.23 按位与
主机地址:0.0.1.23
网络地址:192.168.0.0
子网掩码:255.255.254.0
public class TcpServer {
public static void main(String[] args) {
ServerSocket ss = null;
try {
//1.得到ServerSocket
ss = new ServerSocket(8888);
System.out.println("Server start
...");
//2.等待客户端连接
Socket s = ss.accept();
//3.从Socket中得到输入输出流
InputStream in =
s.getInputStream();
DataInputStream din = new
DataInputStream(in);
String text = din.readUTF();
System.out.println("Server
Receive"+text);
OutputStream out =
s.getOutputStream();
DataOutputStream dout = new
DataOutputStream(out);
dout.writeUTF("你好,客户端");
dout.close();
din.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
try{ss.close();}catch(IOException
e){e.printStackTrace();}
}
}
}
import java.io.*;
import java.net.*;
public class TcpClient {
public static void main(String[] args) {
Socket s = null;
try {
s= new Socket("localhost",8888);
OutputStream out =
s.getOutputStream();
DataOutputStream dout = new
DataOutputStream(out);
dout.writeUTF("你好,服务器");
InputStream in =
s.getInputStream();
DataInputStream din = new
DataInputStream(in);
String text = din.readUTF();
System.out.println("Client
Receive:"+text);
din.close();
dout.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics