1.继承Thread类
源代码:
package com.zy.test.www.multiThread; /** * 多线程实现方式1:继承Thread类 * @author zy */ public class ByExtendsThread extends Thread{ public ByExtendsThread(String name) { super(name); } @Override public void run() { System.out.println(getName() + " 线程运行开始!"); for (int i = 1; i <= 5; i++) { System.out.println(getName() + " " + i); try { sleep((int) Math.random() * 10); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(getName() + " 线程运行结束!"); } public static void main(String[] args) { System.out.println(Thread.currentThread().getName() + " 线程运行开始!"); new ByExtendsThread("A").start(); new ByExtendsThread("B").start(); System.out.println(Thread.currentThread().getName() + " 线程运行结束!"); } }
运行效果:
main 线程运行开始!A 线程运行开始!main 线程运行结束!A 1B 线程运行开始!B 1A 2B 2A 3B 3A 4B 4A 5B 5A 线程运行结束!B 线程运行结束!
2.实现Runnable接口
源代码:
package com.zy.test.www.multiThread; /** * 多线程实现方式2:实现Runnable接口 * @author zy */ public class ByImplementsRunnable implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName() + " 线程运行开始!"); for (int i = 1; i <= 5; i++) { System.out.println(Thread.currentThread().getName() + " " + i); try { Thread.sleep((int) Math.random() * 10); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " 线程运行结束!"); } public static void main(String[] args) { System.out.println(Thread.currentThread().getName() + " 线程运行开始!"); ByImplementsRunnable byImplementsRunnable = new ByImplementsRunnable(); new Thread(byImplementsRunnable, "A").start(); new Thread(byImplementsRunnable, "B").start(); System.out.println(Thread.currentThread().getName() + " 线程运行结束!"); } }
运行效果:
main 线程运行开始! A 线程运行开始! main 线程运行结束! A 1 B 线程运行开始! B 1 A 2 B 2 A 3 B 3 A 4 B 4 A 5 B 5 A 线程运行结束! B 线程运行结束!
时间: 2024-10-12 13:54:46