
在本练习中,您将学习如何通过直接扩展 thread 类(而不是实现 runnable 接口)来在 java 中创建线程。通过这样做,您的类继承了 thread 方法,这使得直接操作线程变得更容易,而不需要实例化单独的线程。
锻炼步骤
扩展 thread 类:
你的类必须继承自 thread 并重写 run() 方法。
类构造函数:
使用 super(name) 构造函数为线程命名,并通过直接调用 start() 开始执行。
重写 run() 方法:
该方法定义了线程的行为。在这里,线程打印它的名称并运行一个循环。
完整的功能示例:
下面是代码:
// define a classe que estende thread
class mythread extends thread {
// constrói uma nova thread
mythread(string name) {
super(name); // nomeia a thread
start(); // inicia a thread
}
// começa a execução da nova thread
public void run() {
system.out.println(getname() + " starting.");
try {
for (int count = 0; count < 10; count++) {
thread.sleep(400); // pausa por 400ms
system.out.println("in " + getname() + ", count is " + count);
}
} catch (interruptedexception exc) {
system.out.println(getname() + " interrupted.");
}
system.out.println(getname() + " terminating.");
}
}
// classe principal para demonstrar a execução das threads
class extendthread {
public static void main(string[] args) {
system.out.println("main thread starting.");
// cria uma nova thread
mythread mt = new mythread("child #1");
// executa a thread principal
for (int i = 0; i < 50; i++) {
system.out.print(".");
try {
thread.sleep(100); // pausa por 100ms
} catch (interruptedexception exc) {
system.out.println("main thread interrupted.");
}
}
system.out.println("main thread ending.");
}
}
代码如何工作
辅助线程创建:
“child #1”线程被创建并通过 start() 立即启动。
辅助线程执行:
该线程执行一个循环,打印消息并在迭代之间暂停 400 毫秒。
主线程执行:
同时,主线程以 100 毫秒的间隔打印点(“.”)。
程序输出(示例)
Main thread starting. Child #1 starting. .In Child #1, count is 0 ..In Child #1, count is 1 ...In Child #1, count is 2 ... (continua) Main thread ending. Child #1 terminating.
观察
主线程和辅助线程同时运行。
run()方法包含了辅助线程的逻辑,而主线程则继续独立执行。
以上就是练习尝试这个扩展线程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号