java并发
java并发是什么
多线程程序包含两个或多个可同时运行的部分,每个部分可以同时处理不同的任务,从而能更好地利用可用资源,特别是当您的计算机有多个CPU时。多线程使您能够写入多个活动,可以在同一程序中同时进行操作处理。
线程的生命周期
线程生命周期的阶段
新线程(New) - 新线程在新的状态下开始其生命周期。直到程序启动线程为止,它保持在这种状态。它也被称为出生线程。
可运行(Runnable) - 新诞生的线程启动后,该线程可以运行。状态的线程被认为正在执行其任务。
等待(Waiting) - 有时,线程会转换到等待状态,而线程等待另一个线程执行任务。 只有当另一个线程发信号通知等待线程才能继续执行时,线程才转回到可运行状态。
定时等待(Timed Waiting) - 可运行的线程可以在指定的时间间隔内进入定时等待状态。 当该时间间隔到期或发生等待的事件时,此状态的线程将转换回可运行状态。
终止(Dead) - 可执行线程在完成任务或以其他方式终止时进入终止状态。
具体实列(建议使用:实现Runnable接口来实现多线程)
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
}catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
运行的结果
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.