2017年计算机二级考试时间_2017年计算机二级考试java章节辅导:多线程例子

副标题:2017年计算机二级考试java章节辅导:多线程例子

时间:2024-01-07 09:24:01 阅读: 最新文章 文档下载
说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。


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

本文来源:https://www.wddqw.com/L9QI.html