原文网址:Java多线程--三种写法(Thread、Runnable、Callable)_IT利刃出鞘的博客-CSDN博客
简介
本文介绍Java多线程的三种写法(Thread、Runnable、Callable)。
写法1:继承 Thread 类
java
package com.example.a;
class TestThread extends Thread {
private String name;
public TestThread(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(name + "运行,i = " + i);
}
}
}
public class Demo {
public static void main(String[] args) {
Thread thread1 = new TestThread("线程 A");
Thread thread2 = new TestThread("线程 B");
// 不能使用run(),因为它不会去启动多线程
thread1.start();
thread2.start();
}
}
运行结果
java
线程 A运行,i = 0
线程 B运行,i = 0
线程 A运行,i = 1
线程 B运行,i = 1
线程 B运行,i = 2
线程 B运行,i = 3
线程 B运行,i = 4
线程 B运行,i = 5
线程 B运行,i = 6
线程 B运行,i = 7
线程 B运行,i = 8
线程 A运行,i = 2
线程 A运行,i = 3
线程 B运行,i = 9
线程 A运行,i = 4
线程 A运行,i = 5
线程 A运行,i = 6
线程 A运行,i = 7
线程 A运行,i = 8
线程 A运行,i = 9
写法2:实现 Runnable 接口
实例
java
package com.example.a;
class TestThread implements Runnable {
private String name;
public TestThread(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(name + "运行,i = " + i);
}
}
}
public class Demo {
public static void main(String[] args) {
TestThread thread1 = new TestThread("线程 A");
TestThread thread2 = new TestThread("线程 B");
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
t1.start();
t2.start();
}
}
运行结果
java
线程 B运行,i = 0
线程 B运行,i = 1
线程 A运行,i = 0
线程 B运行,i = 2
线程 B运行,i = 3
线程 B运行,i = 4
线程 B运行,i = 5
线程 B运行,i = 6
线程 B运行,i = 7
线程 A运行,i = 1
线程 A运行,i = 2
线程 A运行,i = 3
线程 A运行,i = 4
线程 A运行,i = 5
线程 A运行,i = 6
线程 A运行,i = 7
线程 A运行,i = 8
线程 A运行,i = 9
线程 B运行,i = 8
线程 B运行,i = 9
Thread类和Runnable接口的区别
上边是文章的部分内容,为统一维护,全文已转移到此网址:Java多线程-三种写法(Thread、Runnable、Callable) - 自学精灵