當前位置:才華齋>IT認證>NIIT認證>

NIIT認證面試真題及答案

NIIT認證 閱讀(2.67W)

執行緒總是由作業系統佔有和管理,一個新執行緒的建立和啟動只能由作業系統來負責管理。故不能直接呼叫該執行緒的run方法,若如此,則不會建立新的`執行緒和啟動該執行緒,而是和其它類物件一樣,那麼應該怎樣正確啟動執行緒呢?呼叫執行緒物件的start方法。當呼叫Thread物件的start方法時,就會呼叫一個本地的程式碼,該程式碼負責是作業系統初始化一個新的執行緒,並由這個執行緒類執行Thread物件的run方法。

NIIT認證面試真題及答案

建立一個執行緒有兩種方式:其一是繼承Thread類並重載run方法;其二是實現Runnable介面

  第一種方法的程式碼如下:

import .*;

import .*;

class ThreadTest {

/**

* Method main

*

*

* @param args

*

*/

public static void main(String[] args) {

// Create three threads

CustomThread first=new CustomThread("Hopalong ","Cassidy ",200l);

CustomThread second=new CustomThread("Marilyn ","Monroe ",300l);

CustomThread third=new CustomThread("Slim ","Pickens ",500l);

tln("Press Enter when you hava had enought...");

t();

t();

t();

try{

();// Wait until Enter key pressed

tln("Enter pressed...");

}

catch(IOException e){// Handle IO Exception

tln(e );// Output the exception

}

tln("Ending main()...");

return;

}

// Inner class

private static class CustomThread extends Thread{

// Constructor

public CustomThread(String firstName,String secondName,long aWhile){

tName=firstName;

ndName=secondName;

le=aWhile;

aemon(true);

}

// override run method

public void run(){

try{

while(true){

sp; tln(tName);

p(aWhile);

tln(ndName);

}

}

catch(InterruptedException e){

tln(firstName+secondName+e);

}

}

// Constants and Variables

private String firstName;

private String secondName;

private long aWhile;

}

}

  第二種建立執行緒的方法程式碼如下:

import .*;

import .*;

class ThreadTest1 {

/**

* Method main

* @param args

*/

public static void main(String[] args) {

// Create three threads

Thread first=new Thread(new CustomThread("Hopalong ","Cassidy ",200l));

Thread second=new Thread(new CustomThread("Marilyn ","Monroe ",300l));

Thread third=new Thread(new CustomThread("Slim ","Pickens ",500l));

tln("Press Enter when you hava had enought...");

aemon(true);

aemon(true);

aemon(true);

t();

t();

t();

try{

();// Wait until Enter key pressed

tln("Enter pressed...");

}

catch(IOException e){// Handle IO Exception

tln(e );// Output the exception

}

tln("Ending main()...");

return;

}

// Inner class

Private static class CustomThread implements Runnable{

// Constructor

public CustomThread(String firstName,String secondName,long aWhile){

tName=firstName;

ndName=secondName;

le=aWhile;

}

// override run method

public void run(){

try{ 

while(true){

tln(tName);

p(aWhile);

tln(ndName);

}

}

catch(InterruptedException e){

tln(firstName+secondName+e);

}

} 

// Constants and Variables

private String firstName;

private String secondName;

private long aWhile;

}

}