
7.2.2 多线程例子
下面这个例子创建了三个单独的线程,它们分别打印自己的“Hello World":
//Define our simple threads.They will pause for a short time
//and then print out their names and delay times
public class TestThread extends Thread {
private String whoami; //定义其属性
private int delay;
//Our constructor to store the name (whoami)
//and time to sleep (delay)
public TestThread(String s, int d) { //定义了一个线程的构造函数
whoami = s;
delay = d;
}
//Run - the thread method similar to main()
//When run is finished, the thread dies.
//Run is called from the start() method of Thread
public void run() { //运行线程
//Try to sleep for the specified time
try {
sleep(delay); //让线程进行睡眠
}
catch(InterruptedException e) {
}
//Now print out our name
System.out.println("Hello World!"+whoami+""+delay);
}
}
/** * Multimtest. A simple multithread thest program */
public static void main(String[] args) {
TestThread t1,t2,t3;
//Create our test threads
t1 = new TestThread("Thread1",(int)(Math.readom()*2000)); //实例化线程
t2 = new TestThread("Thread2",(int)(Math.readom()*2000));
t3 = new TestThread("Thread3",(int)(Math.readom()*2000));
//Start each of the threads
t1.start(); //启动线程
t2.start();
t3.start();
}
}
7.2.3 启动一个线程
程序启动时总是调用main()函数,因此main()是我们创建和启动线程的地方:
t1 = new TestThread("Thread1", (int)(Math.readom()*2000));
这一行创建了一个新的线程。后面的两个参数传递了线程的名称和线程在打印信息前的延 时时间。因为我们直接控制线程,我们必须直接启动它:
t1.start();
2017年计算机二级考试java章节辅导:多线程例子.doc正在阅读:
2017年计算机二级考试java章节辅导:多线程例子01-07
移民英国的小常识介绍03-30
喜迎七一建党节经典祝福词11-14
经济信息管理毕业论文开题报告_经济管理学毕业论文开题报告08-18
《阿凡达2》电影影片观后感心得04-07
军人入党申请书格式【三篇】07-07
2019山西太原幼升小之学区房购置攻略08-19
“人”的味道作文01-28