java面試題二

來源:互聯網
上載者:User

package com.softeem.demo;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
*@authorleno
*單子模式,保證在整個應用期間只載入一次配置屬性檔案
*/
publicclass Singleton {

    privatestatic Singleton instance;
    privatestaticfinal String CONFIG_FILE_PATH = "E:\\config.properties";
    private Properties config;
    private Singleton()
    {
      config = new Properties();
      InputStream is;
      try {
          is = new FileInputStream(CONFIG_FILE_PATH);
          config.load(is);
          is.close();
      } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
    }
    publicstatic Singleton getInstance()
    {
      if(instance==null)
      {
          instance = new Singleton();
      }
      returninstance;
    }
    public Properties getConfig() {
      returnconfig;
    }
    publicvoid setConfig(Properties config) {
      this.config = config;
    }
   
   

}
l    J2SE
19.拷貝一個目錄(檔案)到指定路徑
/**
    *拷貝一個目錄或者檔案到指定路徑下
    *@paramsource
    *@paramtarget
    */
    publicvoid copy(File source,File target)
    {
      File tarpath = new File(target,source.getName());
      if(source.isDirectory())
      {
          tarpath.mkdir();
          File[] dir = source.listFiles();
          for (int i = 0; i < dir.length; i++) {
              copy(dir[i],tarpath);
          }
      }else
      {
          try {
              InputStream is = new FileInputStream(source);
              OutputStream os = new FileOutputStream(tarpath);
              byte[] buf = newbyte[1024];
              int len = 0;
              while((len = is.read(buf))!=-1)
              {
                  os.write(buf,0,len);
              }
              is.close();
              os.close();
          } catch (FileNotFoundException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
    }
20.用JAVA中的多線程樣本銀行取款問題
packagecom.softeem.demo;

/**
*@authorleno
*賬戶類
*預設有餘額,可以取款
*/
class Account {
    privatefloatbalance = 1000;

    publicfloat getBalance() {
      returnbalance;
    }

    publicvoid setBalance(float balance) {
      this.balance = balance;
    }
   
    /**
    *取款的方法需要同步
    *@parammoney
    */
    publicsynchronizedvoid withdrawals(float money)
    {
      if(balance>=money)
      {
          System.out.println("被取走"+money+"元!");
          try {
              Thread.sleep(1000);
          } catch (InterruptedException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
          balance-=money;
      }
      else
      {
          System.out.println("對不起,餘額不足!");
      }
    }
   
}

/**
*@authorleno
*銀行卡
*/
class TestAccount1 extends Thread {

    private Account account;
   
   
    public TestAccount1(Account account) {
      this.account = account;
    }


    @Override
    publicvoid run() {
      account.withdrawals(800);
      System.out.println("餘額為:"+account.getBalance()+"元!");
    } 
}
/**
*@authorleno
*存摺
*/
class TestAccount2 extends Thread {

    private Account account;
    public TestAccount2(Account account) {
          this.account = account;
      }
    @Override
    publicvoid run() {
      account.withdrawals(700);
      System.out.println("餘額為:"+account.getBalance()+"元!");
    } 
}

publicclass Test
{
    publicstaticvoid main(String[] args) {
      Account account = new Account();
      TestAccount1 testAccount1 = new TestAccount1(account);
      testAccount1.start();
      TestAccount2 testAccount2 = new TestAccount2(account);
      testAccount2.start();
    }
}
21.用JAVA中的多線程樣本火車站售票問題
package com.softeem.demo;

/**
*@authorleno
*售票類
*/
class SaleTicket implements Runnable {
    inttickets = 100;

    publicvoid run() {
      while (tickets > 0) {
          sale();
//或者下面這樣實現
//        synchronized (this) {
//            if (tickets > 0) {
//                System.out.println(Thread.currentThread().getName() + "賣第"
//                      + (100 - tickets + 1) + "張票");
//                tickets--;
//            }
//        }
      }
    }

    publicsynchronizedvoid sale() {
      if (tickets > 0) {
          System.out.println(Thread.currentThread().getName() + "賣第"
                  + (100 - tickets + 1) + "張票");
          tickets--;
      }
    }

}

publicclass TestSaleTicket {

    publicstaticvoid main(String[] args) {
      SaleTicket st = new SaleTicket();
      new Thread(st, "一號視窗").start();
      new Thread(st, "二號視窗").start();
      new Thread(st, "三號視窗").start();
      new Thread(st, "四號視窗").start();

    }
}

22.用JAVA中的多線程樣本生產者和消費者問題
package com.softeem.demo;

class Producer implements Runnable
{
private SyncStack stack;

    public Producer(SyncStack stack) {
    this.stack = stack;
}

    publicvoid run() {
      for (int i = 0; i < stack.getProducts().length; i++) {
          String product = "產品"+i;
          stack.push(product);
          System.out.println("生產了: "+product);
          try
          {
            Thread.sleep(200);
          }
          catch(InterruptedException e)
          {
            e.printStackTrace();
          }


      }
    }
   
}

class Consumer implements Runnable
{
    private SyncStack stack;

    public Consumer(SyncStack stack) {
    this.stack = stack;
}
    publicvoid run() {
      for(int i=0;i <stack.getProducts().length;i++)
          {
          String product =stack.pop();
          System.out.println("消費了: "+product);
          try
          {
            Thread.sleep(1000);
          }
          catch(InterruptedException e)
          {
            e.printStackTrace();
          }

          }

     
    }
}

class SyncStack
{
    private String[] products = new String[10];
    privateintindex;
    publicsynchronizedvoid push(String product)
    {
      if(index==product.length())
      {
          try {
              wait();
          } catch (InterruptedException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
      notify();
      products[index]=product;
      index++;
    }
   
    publicsynchronized String pop()
    {
      if(index==0)
      {
          try {
              wait();
          } catch (InterruptedException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
      notify();
      index--;
      String product = products[index];
      return product;
    }

    public String[] getProducts() {
      returnproducts;
    }
   
   
}
publicclass TestProducerConsumer {
   
    publicstaticvoid main(String[] args) {
      SyncStack stack=new SyncStack();
      Producer p=new Producer(stack);
      Consumer c=new Consumer(stack);

      new Thread(p).start();
      new Thread(c).start();
      }
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.