Java Interview Question 2

Source: Internet
Author: User
Tags sleep ticket

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
* The configuration attribute file is loaded only once during the entire application.
*/
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. Copy a directory (file) to the specified path
/**
* Copy a directory or file to a specified path
* @ 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 [1, 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. Example of bank withdrawal using multithreading in JAVA
Packagecom. softeem. demo;

/**
* @ Authorleno
* Account type
* The account has a balance by default and can be withdrawn.
*/
Class Account {
Privatefloatbalance = 1000;

Publicfloat getBalance (){
Returnbalance;
    }

Publicvoid setBalance (float balance ){
This. balance = balance;
    }
   
/**
* The withdrawal method must be synchronized.
* @ Parammoney
*/
Publicsynchronizedvoid withdrawals (float money)
    {
If (balance> = money)
      {
System. out. println ("removed" + money + "RMB! ");
Try {
Thread. sleep (1000 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
          }
Balance-= money;
      }
Else
      {
System. out. println ("Sorry, the balance is insufficient! ");
      }
    }
   
}

/**
* @ Authorleno
* Bank card
*/
Class TestAccount1 extends Thread {

Private Account account;
   
   
Public TestAccount1 (Account account Account ){
This. account = account;
    }


@ Override
Publicvoid run (){
Account. withdrawals (800 );
System. out. println ("balance:" + account. getBalance () + "RMB! ");
    } 
}
/**
* @ Authorleno
* Passbook
*/
Class TestAccount2 extends Thread {

Private Account account;
Public TestAccount2 (Account account Account ){
This. account = account;
      }
@ Override
Publicvoid run (){
Account. withdrawals (700 );
System. out. println ("balance:" + account. getBalance () + "RMB! ");
    } 
}

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. Example of train station ticket sales using multithreading in JAVA
Package com. softeem. demo;

/**
* @ Authorleno
* Ticket sales
*/
Class SaleTicket implements Runnable {
Inttickets = 100;

Publicvoid run (){
While (tickets> 0 ){
Sale ();
// Or the following implementation
// Synchronized (this ){
// If (tickets> 0 ){
// System. out. println (Thread. currentThread (). getName () + "seller"
// + (100-tickets + 1) + "tickets ");
// Tickets --;
//}
//}
      }
    }

Publicsynchronizedvoid sale (){
If (tickets> 0 ){
System. out. println (Thread. currentThread (). getName () + "seller"
+ (100-tickets + 1) + "tickets ");
Tickets --;
      }
    }

}

Publicclass TestSaleTicket {

Publicstaticvoid main (String [] args ){
SaleTicket st = new SaleTicket ();
New Thread (st, "Window 1"). start ();
New Thread (st, "Window 2"). start ();
New Thread (st, "Window 3"). start ();
New Thread (st, "Window No. 4"). start ();

    }
}

22. Sample producer and consumer issues using multithreading in 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 = "product" + I;
Stack. push (product );
System. out. println ("produced:" + 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 ("consumed:" + 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 ();
      }
    }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.