标签:
源代码:
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 1
B 线程运行开始!
B 1
A 2
B 2
A 3
B 3
A 4
B 4
A 5
B 5
A 线程运行结束!
B 线程运行结束!
源代码:
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 线程运行结束!
标签:
原文地址:http://www.cnblogs.com/sunny08/p/4866137.html