
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
[2022年中考成绩查询时间]2022年安徽省宿州市中考成绩查询网站:http://jiaotiju.ahsz.gov.cn/05-17
怀念家乡的作文600字|怀念家乡的耕牛作文600字02-03
入党流程介绍心得体会,入党流程及时间介绍05-09
成长过程中的烦恼作文800字12-12
2017上半年陕西人力资源管理师准考证打印时间:考前一周内11-01
圣诞节活动主持词优秀范文01-26
2020年内科医生个人工作计划|2020年内科医生工作计划模板01-27
公羊传:《昭公二十七年》原文译文02-22