知ing

Java面向对象程序设计

耿祥义,张跃平 编 / 清华大学出版社

青涩当初 上传

查看本书


习题15

14种状态:新建、运行、中断和死亡。

2.有4种原因的中断:(1JVMCPU资源从当前线程切换给其他线程,使本线程让出CPU的使用权处于中断状态。(2)线程使用CPU资源期间,执行了sleep(int millsecond)方法,使当前线程进入休眠状态。经过参数millsecond指定的豪秒数之后,该线程就重新进到线程队列中排队等待CPU资源,以便从中断处继续运行。(3)线程使用CPU资源期间,执行了wait()方法,使得当前线程进入等待状态。等待状态的线程不会主动进到线程队列中排队等待CPU资源,必须由其他线程调用notify()方法通知它,使得它重新进到线程队列中排队等待CPU资源,以便从中断处继续运行。(4)线程使用CPU资源期间,执行某个操作进入阻塞状态,比如执行读/写操作引起阻塞。进入阻塞状态时线程不能进入排队队列,只有当引起阻塞的原因消除时,线程才重新进到线程队列中排队等待CPU资源,以便从原来中断处开始继续运行。

3.死亡状态,不能再调用start()方法。

4.新建和死亡状态。

5.两种方法:用Thread类或其子类。

6.使用 setPrority(int grade)方法。

7Java使我们可以创建多个线程,在处理多线程问题时,我们必须注意这样一个问题:当两个或多个线程同时访问同一个变量,并且一个线程需要修改这个变量。我们应对这样的问题作出处理,否则可能发生混乱。

8.当一个线程使用的同步方法中用到某个变量,而此变量又需要其它线程修改后才能符合本线程的需要,那么可以在同步方法中使用wait()方法。使用wait方法可以中断方法的执行,使本线程等待,暂时让出CPU的使用权,并允许其它线程使用这个同步方法。其它线程如果在使用这个同步方法时不需要等待,那么它使用完这个同步方法的同时,应当用notifyAll()方法通知所有的由于使用这个同步方法而处于等待的线程结束等待

9.不合理。

10“吵醒”休眠的线程。一个占有CPU资源的线程可以让休眠的线程调用interrupt 方法“吵醒”自己,即导致休眠的线程发生InterruptedException异常,从而结束休眠,重新排队等待CPU资源。

11

public class Xiti11

{ public static void main(String args[])

    {   Cinema a=new Cinema();

        a.zhang.start();

        a.sun.start();

        a.zhao.start();

    }

}

class TicketSeller    //负责卖票的类。

{  int fiveNumber=3,tenNumber=0,twentyNumber=0;

   public synchronized void  sellTicket(int receiveMoney)

   {  if(receiveMoney==5)

       {  fiveNumber=fiveNumber+1;

          System.out.println(Thread.currentThread().getName()+

"给我5元钱,这是您的1张入场卷");

       }

       else if(receiveMoney==10)           

        { while(fiveNumber<1)

            {   try {  System.out.println(Thread.currentThread().getName()+"靠边等");

                       wait();   

                       System.out.println(Thread.currentThread().getName()+"结束等待");

                    }

               catch(InterruptedException e) {}

            }

           fiveNumber=fiveNumber-1;

           tenNumber=tenNumber+1;

           System.out.println(Thread.currentThread().getName()+

"给我10元钱,找您5,这是您的1张入场卷");  

        }

       else if(receiveMoney==20)           

        {  while(fiveNumber<1||tenNumber<1)

            {   try {  System.out.println(Thread.currentThread().getName()+"靠边等");

                       wait();   

                       System.out.println(Thread.currentThread().getName()+"结束等待");

                    }

               catch(InterruptedException e) {}

            }

           fiveNumber=fiveNumber-1;

           tenNumber=tenNumber-1;

           twentyNumber=twentyNumber+1;   

           System.out.println(Thread.currentThread().getName()+

"20元钱,找您一张5元和一张10元,这是您的1张入场卷");

                             

        }

       notifyAll();

   }

}

class Cinema implements Runnable          

{  Thread zhang,sun,zhao;

   TicketSeller seller;

   Cinema()

   {  zhang=new Thread(this);

      sun=new Thread(this);

      zhao=new Thread(this);

      zhang.setName("张小有");

      sun.setName("孙大名");

      zhao.setName("赵中堂");

      seller=new TicketSeller();

   }

   public void run()

   {  if(Thread.currentThread()==zhang)

       {  seller.sellTicket(20);

       }

       else if(Thread.currentThread()==sun)

       {  seller.sellTicket(10);

       }

       else if(Thread.currentThread()==zhao)

       { seller.sellTicket(5);

       }

   }

}

12参照本章例子9。

13参照本章例子19。

14BA

习题16

1URL对象调用InputStream openStream() 方法可以返回一个输入流。

2.客户端的程序使用Socket类建立负责连接到服务器的套接字对象称为socket对象。
使用Socket的构造方法Socket(String  host,int port)建立连接到服务器的套接字对象参考16.3.2

3JEditorPane

4会返回一个和客户端Socket对象相连接的Socket对象

5域名/IP 地址  例如,www.sina.com.cn/202.108.35.210

6

(1) 客户端

import java.net.*;

import java.io.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Client

{  public static void main(String args[])

   {  new ComputerClient();

   }

}

class ComputerClient extends Frame implements Runnable,ActionListener

{  Button connection,send;

   TextField inputText,showResult;

   Socket socket=null;

   DataInputStream in=null;

   DataOutputStream out=null;

   Thread thread;

   ComputerClient()

   {  socket=new Socket();

      setLayout(new FlowLayout());

      Box box=Box.createVerticalBox();

      connection=new Button("连接服务器");

      send=new Button("发送");

      send.setEnabled(false);

      inputText=new TextField(12);

      showResult=new TextField(12);

      box.add(connection);

      box.add(new Label("输入三角形三边的长度,用逗号或空格分隔:"));

      box.add(inputText);

      box.add(send);

      box.add(new Label("收到的结果:"));

      box.add(showResult);

      connection.addActionListener(this);

      send.addActionListener(this);

      thread=new Thread(this);

      add(box);

      setBounds(10,30,300,400);

      setVisible(true);

      validate();

      addWindowListener(new WindowAdapter()

                   {  public void windowClosing(WindowEvent e)

                            {  System.exit(0);

                            }

                   });

   }

   public void actionPerformed(ActionEvent e)

   { if(e.getSource()==connection)

      {  try  //请求和服务器建立套接字连接:

         { if(socket.isConnected())

              {}

           else

              { InetAddress  address=InetAddress.getByName("127.0.0.1");

                InetSocketAddress socketAddress=new InetSocketAddress(address,4331);

                socket.connect(socketAddress);

                in =new DataInputStream(socket.getInputStream());

                out = new DataOutputStream(socket.getOutputStream());

                send.setEnabled(true);

                thread.start();

               }

         }

         catch (IOException ee){}

      }

     if(e.getSource()==send)

      {  String s=inputText.getText();

         if(s!=null)

           {  try { out.writeUTF(s);

                  }

              catch(IOException e1){}

           }               

      }

   }

   public void run()

   {  String s=null;

      while(true)

       {    try{  s=in.readUTF();

                  showResult.setText(s);

               }

           catch(IOException e)

               {  showResult.setText("与服务器已断开");

                      break;

               }   

       }

  }

}

2)服务器端

import java.io.*;

import java.net.*;

import java.util.*;

public class Server

{  public static void main(String args[])

   {  ServerSocket server=null;

      Server_thread thread;

      Socket you=null;

      while(true)

       {  try{  server=new ServerSocket(4331);

             }

          catch(IOException e1)

             {  System.out.println("正在监听"); //ServerSocket对象不能重复创建

             }

          try{  System.out.println(" 等待客户呼叫");

                you=server.accept();

                System.out.println("客户的地址:"+you.getInetAddress());

             }

         catch (IOException e)

             {  System.out.println("正在等待客户");

             }

         if(you!=null)

               {  new Server_thread(you).start(); //为每个客户启动一个专门的线程  

             }

       }

   }

}

class Server_thread extends Thread

{  Socket socket;

   DataOutputStream out=null;

   DataInputStream  in=null;

   String s=null;

   boolean quesion=false;

   Server_thread(Socket t)

   {  socket=t;

      try {  out=new DataOutputStream(socket.getOutputStream());

             in=new DataInputStream(socket.getInputStream());

          }

      catch (IOException e)

          {}

   }  

   public void run()        

   {  while(true)

      {  double a[]=new double[3] ;

         int i=0;

         try{  s=in.readUTF();//堵塞状态,除非读取到信息

               quesion=false;

               StringTokenizer fenxi=new StringTokenizer(s," ,");

                 while(fenxi.hasMoreTokens())

                   {  String temp=fenxi.nextToken();

                      try{  a[i]=Double.valueOf(temp).doubleValue();i++;

                         }

                      catch(NumberFormatException e)

                         {  out.writeUTF("请输入数字字符");

                            quesion=true;

                         }

                   }

                if(quesion==false)

                {  double p=(a[0]+a[1]+a[2])/2.0;

                   out.writeUTF(" "+Math.sqrt(p*(p-a[0])*(p-a[1])*(p-a[2])));

                }

            }

         catch (IOException e)

            {  System.out.println("客户离开");

               return;

            }

      }

   }

}

7.参照本章例子16.6及以下代码。

1)服务器

Server.java

import java.io.*;

import java.net.*;

import java.util.zip.*;

public class Server

{  public static void main(String args[])

   {  ServerSocket server=null;

      ServerThread thread;

      Socket you=null;

      while(true)

       {   try{  server=new ServerSocket(4331);

              }

          catch(IOException e1)

             {   System.out.println("正在监听");  

             }

          try{  you=server.accept();

                System.out.println("客户的地址:"+you.getInetAddress());

             }

         catch (IOException e)

             {  System.out.println("正在等待客户");

             }

         if(you!=null)

             {  new ServerThread(you).start();  

             }

       }

   }

}

class ServerThread extends Thread

{  Socket socket;

   ZipOutputStream out;

   String s=null;

   ServerThread(Socket t)

   {  socket=t;

      try  {  out=new ZipOutputStream(socket.getOutputStream());

           }

      catch (IOException e){}  

   }

   public void run()        

   {  try{out.putNextEntry(new ZipEntry("Example.java"));

          FileInputStream reader=new FileInputStream("Example.java");

          byte b[]=new byte[1024];

          int n=-1;

          while((n=reader.read(b,0,1024))!=-1)

          { out.write(b,0,n);              //发送压缩后的数据到客户端。

          }

          out.putNextEntry(new ZipEntry("E.java"));

          reader=new FileInputStream("E.java");

          n=-1;

          while((n=reader.read(b,0,1024))!=-1)

          { out.write(b,0,n);               //发送压缩后的数据到客户端。

          }  

         reader.close();

         out.close();

        }

     catch (IOException e) {}

   }

}

2)客户端

Client.java

import java.net.*;

import java.io.*;

import java.awt.*;

import java.awt.event.*;

import java.util.zip.*;

public class Client extends Frame implements Runnable,ActionListener

{  Button connection,getFile;

   TextArea showResult;

   Socket socket=null;

   ZipInputStream in;

   Thread thread;

   public  Client()

   {  socket=new Socket();              

      connection=new Button("连接服务器,获取文件内容");

      setLayout(new FlowLayout());

      showResult=new TextArea(10,28);

      add(connection);

      add(showResult);

      connection.addActionListener(this);

      thread=new Thread(this);

      setBounds(100,100,460,410);

      setVisible(true);

      addWindowListener(new WindowAdapter()

                   {  public void windowClosing(WindowEvent e)

                            {  System.exit(0);

                            }

                   });

   }

   public void run()

   { byte b[]=new byte[1024];

     ZipEntry zipEntry=null;

     while(true)

       { try{  while((zipEntry=in.getNextEntry())!=null)

                   {  showResult.append("\n"+zipEntry.toString()+":\n");

                      int n=-1;

                      while((n=in.read(b,0,1024))!=-1)

                       {  String str=new String(b,0,n);

                          showResult.append(str);

                       }

                   }      

             }

           catch(IOException e) {  }

       }

  }

  public void actionPerformed(ActionEvent e)

  { if(e.getSource()==connection)

    { try { if(socket.isConnected())

              {}

            else

              { InetAddress  address=InetAddress.getByName("127.0.0.1");

                InetSocketAddress socketAddress=new InetSocketAddress(address,4331);

                socket.connect(socketAddress);

                in=new ZipInputStream(socket.getInputStream());

                thread.start();

              }

         }

        catch (IOException ee)

         {  System.out.println(ee);

         }

    }

  }

  public static void main(String args[])

  {  Client win=new  Client();

  }

}

习题17

1

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class Xiti1 extends Applet implements ActionListener{

   Button button;

   TextField text;

   int sum;

   public void init() {

      button=new Button("点点看...");

      text=new TextField(20);  

      add(button);

      add(text);  

      button.addActionListener(this);   

   }

   public void actionPerformed(ActionEvent e){

      String str=button.getLabel();

      text.setText("按钮上写着:"+str);

   }

}

超文本文件:

<applet code=Xiti1.class height=180 width=300>

</applet>

2

import java.applet.*;

import java.awt.*;

import java.awt.event.*;  

import javax.swing.*;

public class Xiti2 extends Applet implements ActionListener

{  TextField text1,text2;

   Label label;

   public void init()

   {  text1=new TextField(10);

      text2=new TextField(20);

      Box box1=Box.createHorizontalBox();

      Box box2=Box.createHorizontalBox();

      Box boxV=Box.createVerticalBox();

      box1.add(new Label("输入一个数回车确定:"));

      box1.add(text1);

      label=new Label("数的平方:");

      box2.add(label);

      box2.add(text2);

      boxV.add(box1);

      boxV.add(box2);

      add(boxV);

      text2.setEditable(false);

      text1.addActionListener(this);

   }

   public void actionPerformed(ActionEvent e)

   {  String number=e.getActionCommand();

      try{ double n=Double.parseDouble(number);

           double m=n*n;

           label.setText(n+"的平方:");

           text2.setText(""+m);

           text1.setText("");

           validate();

         }

      catch(NumberFormatException exp)

         {  text2.setText(""+exp);

         }

   }

}

3.参照本章例子17.217.3


查看更多