Java语言的JVM允许程序允许多个线程。它通过java.lang.Thread
类来体现。
java通过实现Runable接口实现多线程
- 定义子类,实现Runnable接口。
- 子类中重写Runnable接口中的run方法。
- 通过Thread类含参构造器创建线程对象。
- 将Runnable接口的子类对象作为实际参数传递给Thread类的构造器中。
- 调用Thread类的start方法:开启线程,调用Runnable子类接口的run方法。
// 定义子类继承Thread类
class Thread1 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
public class Solution {
// 创建Thread子类对象,即创建了线程对象。
public static void main(String[] args) throws InterruptedException {
Thread1 runThread = new Thread1();
Thread t1 = new Thread(runThread);
t1.start();
}
}
java通过继承thread类实现多线程
- 定义子类继承Thread类。
- 子类中重写Thread类中的run方法。
- 创建Thread子类对象,即创建了线程对象。
- 调用线程对象start方法:启动线程,调用run方法。
// 定义子类继承Thread类
class MyThread extends Thread{
public MyThread() {
}
//子类中重写Thread类中的run方法。
@Override
public void run() {
for (int i = 0; i < 100000; i++){
if (i % 2 == 0){
// 获取当前线程名字:Thread.currentThread().getName()
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
public class Solution {
// 创建Thread子类对象,即创建了线程对象。
public static void main(String[] args) {
MyThread t1 = new MyThread();
// 调用线程对象start方法:启动线程,调用run方法。
t1.start();
for (int i = 0; i < 100000; i++){
if (i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
补充
start与run的区别
1、如果调用start函数,发现启动了一个叫做Thread-0的线程
2、如果在主函数中通过调用run函数,发现run函数还是会执行的,但是但是由主函数执行,没有发现由子线程启动
- 如果自己手动调用run()方法,那么就只是普通方法,没有启动多线程模式。
- run()方法由JVM调用,什么时候调用,执行的过程控制都有操作系统的CPU
调度决定。 - 想要启动多线程,必须调用start方法。
3、 一个线程对象只能调用一次start()方法启动,如果重复调用了,则将抛出以上
的异常“IllegalThreadStateException”
给线程起名字
1、给主线程起名
// 创建Thread子类对象,即创建了线程对象。
public static void main(String[] args) {
Thread.currentThread().setName("线程线程线程");
System.out.println(Thread.currentThread().getName());
}
2、给子线程起名
(1) 方法一:
// 定义子类继承Thread类
class MyThread extends Thread{
//子类中重写Thread类中的run方法。
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public class Solution {
// 创建Thread子类对象,即创建了线程对象。
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.setName("给子线程起名");
t1.start();
}
}
(2) 方法二
// 定义子类继承Thread类
class MyThread extends Thread{
// 通过构造函数给子线程起名
public MyThread(String name) {
super(name);
}
//子类中重写Thread类中的run方法。
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public class Solution {
// 创建Thread子类对象,即创建了线程对象。
public static void main(String[] args) {
MyThread t1 = new MyThread("给子线程起名");
t1.start();
}
}