创建多线程方式(Java)
一、创建自定义线程类继承Thread
自定义线程类代码
package com.demo05;public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("run:"+i);
}
}
}
测试类
package com.demo05;public class Demo01Thread {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
for (int i = 0; i < 20; i++) {
System.out.println("main:" + i);
}
}
}
二、自定义线程类实现Runnable接口
自定义线程类代码
package com.demo05;public class RunableImp implements Runnable {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("run:"+i);
}
}
}
测试类
package com.demo05;public class Demo02Runable {
public static void main(String[] args) {
RunableImp rt = new RunableImp();
Thread t = new Thread(rt);
t.start();
for (int i = 0; i < 20; i++) {
System.out.println("main:" + i);
}
}
}
三、匿名内部类实现多线程方式
package com.demo05;public class nimingneibuleiThread {
public static void main(String[] args) {
// 使用Thread类创建
new Thread() {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("hello" + i);
}
}
}.start();
// 使用Runnable接口实现
Runnable r = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("world" + i);
}
}
};
new Thread(r).start();
// 简化 Runnable 写法
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("sorry" + i);
}
}
}).start();
}
}
以上是 创建多线程方式(Java) 的全部内容, 来源链接: utcz.com/z/392743.html