练习尝试这个扩展线程
收藏
一分耕耘,一分收获!既然打开了这篇文章《练习尝试这个扩展线程》,就坚持看下去吧!文中内容包含等等知识点…希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

在本练习中,您将学习如何通过直接扩展 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()方法包含了辅助线程的逻辑,而主线程则继续独立执行。
好了,本文到此结束,带大家了解了《练习尝试这个扩展线程》,希望本文对你有所帮助!关注米云公众号,给大家分享更多文章知识!
版本声明 本文转载于:dev.to 如有侵犯,请联系删除
