Java学习

进程和线程

  • 进程是程序的一次执行实例,拥有独立的地址空间、资源(内存、文件句柄等),是资源分配的基本单位
  • 线程是进程中的一个执行单元,共享进程的资源,是CPU调度的基本单位

线程的创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Main{
public static void main(String[] args)
{
System.out.println("main thread");
//创建新进程
Thread t = new Tread() {
//start方法会在内部自动调用实例的run方法
public void run(){
Thread.sleep(10);
System.out.println("New thread");
}
//启动新进程
t.start();
}

};

}

线程的状态

  • New:新创建的线程,尚未执行;
  • Runnable:运行中的线程,正在执行run()方法的Java代码;
  • Blocked:运行中的线程,因为某些操作被阻塞而挂起;
  • Waiting:运行中的线程,因为某些操作在等待中;
  • Timed Waiting:运行中的线程,因为执行sleep()方法正在计时等待;
  • Terminated:线程已终止,因为run()方法执行完毕。
1
2
3
4
5
6
7
8
9
10
11
12
// 多线程
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
System.out.println("hello");
});
System.out.println("start");
t.start(); // 启动t线程
t.join(); // 此处main线程会等待t结束(待其结束后再继续运行)
System.out.println("end");
}
}

线程同步

  • 线程使用synchronized锁住对象,也可修饰函数,确保该线程不会被拆分
  • 如果两个线程互相索要锁,则会陷入死锁状态
  • 使用wait和notify,确保线程进行的顺序
  • 使用ReentrantLock代替synchronized
  • 使用Condition代替wait和notify