多线程一向是提升程序运算效率的一大双刃剑,用好了效率飞快,用坏了出了bug也不知道怎么回事。
一个多线程程序包含两个或多个能并发运行的部分。这些并发的部分能够充分的利用CPU,提高程序的运行效率,他们使用共同的内存空间,属于同一个进程。
可以把多线程当作CPU的进程调度来理解,只不过是级别更低一级的进程调度。同样也有死锁、通信、同步等问题,也有新建、运行、就绪、休眠等状态,也有优先级的概念。
Java对多线程的实现主要用两种
通过实现Runable接口;
通过继承Thread类本身。
使用都非常简单,直接贴code。
class NewThread implements Runnable {
Thread t;
NewThread() {
//创建第二个新线程
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
// 开始线程
t.start();
}
//第二个线程入口
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// 暂停线程
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String args[]) {
//创建一个新线程
new NewThread();
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
和
class NewThread extends Thread {
NewThread() {
//创建第二个新线程
super("Demo Thread");
System.out.println("Child thread: " + this);
//开始线程
start();
}
//第二个线程入口
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
//让线程休眠一会
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ExtendsThread {
public static void main(String args[]) {
//创建一个新线程
new NewThread();
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
另外在JDK8中,对list写foreach的执行也是并发的,这点也是较为常用的。