1、 线程是程序内部的执行过程。
2、 线程和进程的区别
1. 每个进程都有独立的代码和数据空间(进程上下文),进程间的切换会有较大的开销
2. 线程可以看成是轻量级的进程,同一类线程共享代码和数据空间,每个线程有独立的运行栈和程序计数器 (PC), 线程的切换开销小。
3. 在操作系统中同时运行多个任务程序叫做多进程。
4. 在同一应用程序中有多个程序控制流同时执行叫做多线程。
下面的程序开始到结束只有一条执行线索
package com.thread;
// 这个程序只有一条执行线索,用 Debug 模式观察更为清晰
public class TestSingle {
Thread a = new Thread();
public static void main(String [] args) {
fn1 ();
}
private static void fn1() {
System. out .println( "fn1" );
fn2 ();
fn3 ();
}
private static void fn2() {
System. out .println( "fn2" );
}
private static void fn3() {
System. out .println( "fn3" );
}
}
| |
线程同步
|
|
package com.thread.sync;
// 如果不加 synchronized ,当 m1 被锁定的时候, m2 也能执行,是道面试
public class TT implements Runnable {
int a = 100;
public synchronized void m1() throws InterruptedException {
System. out .println( "m1start..." );
a = 1000;
Thread.sleep (5000);
System. out .println( "m1:" + a );
System. out .println( "m1end..." );
}
// 如果这里加上 synchronized ,当 m2 执行的时候,
// 拿到了当前对象的锁, m1 不能执行,理解互斥锁。
public /*synchronized*/ void m2() throws InterruptedException {
System. out .println( "m2start......" );
Thread.sleep (2500);
a = 2000;
System. out .println( "m2end..." );
}
@Override
public void run() {
try {
m1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
System. out .println( "mainstart..." );
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
System. out .println( "main:" + tt. a );
}
}
| |
wait
使正在当前对象访问的线程 wait, 当 wait 时,对象的锁不在归对象的线程所有!