NIIT認證面試真題及答案

線程總是由操作系統佔有和管理,一個新線程的創建和啓動只能由操作系統來負責管理。故不能直接調用該線程的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;

}

}