NIIT认证面试真题及答案
线程总是由操作系统占有和管理,一个新线程的创建和启动只能由操作系统来负责管理。故不能直接调用该线程的run方法,若如此,则不会创建新的`线程和启动该线程,而是和其它类对象一样,那么应该怎样正确启动线程呢?调用线程对象的start方法。当调用Thread对象的start方法时,就会调用一个本地的代码,该代码负责是操作系统初始化一个新的线程,并由这个线程类执行Thread对象的run方法。
创建一个线程有两种方式:其一是继承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;
}
}