线程是指程序中单独顺序的流控制,线程本身不能运行,只能用于程序中。
多线程是指单个程序中可以同时运行多个不容的线程执行不能任务。
1:继承于Thread
一个简单的打印数字作为列子
package com.sun.print;
public class PrintNumber extends Thread {
public PrintNumber(String name) {
super(name);
}
@Override
public void run() {
String threadName = getName();
try {
for (int i = 1; i <= 20; i++) {
System.out.printf("%s:%d/n", threadName, i);
sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
PrintNumber a = new PrintNumber("number1");
PrintNumber b = new PrintNumber("number2");
a.start();
b.start();
}
}
2:实现Runnable接口
package com.sun.print;
public class Print implements Runnable {
public void run() {
String threadName = Thread.currentThread().getName();
try {
for (int i = 1; i <= 20; i++) {
System.out.printf("%s:%d/n", threadName, i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Print runnable = new Print();
Thread a = new Thread(runnable, "number1");
Thread b = new Thread(runnable, "number2");
a.start();
b.start();
try {
b.join();
System.out.println("join");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}