进程与线程的区别
1.进程:是系统进行分配和管理资源的基本单位
2.线程:进程的一个执行单元,是进程内调度的实体、是CPU调度和分派的基本单位,是比进程更小的独立运行的基本单位。线程也被称为轻量级进程,线程是程序执行的最小单位。
一个程序至少一个进程,一个进程至少一个线程。
线程状态的相互转换
线程的创建
1.继承Thread,并重写父类的run方法
public class MyThread extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.setName("我是一个线程");
myThread.start();
}
}
2.实现Runable接口,并实现run方法
public class MyRunable implements Runnable,Serializable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread thread = new Thread(new MyRunable());
thread.setName("我是一个线程");
thread.start();
//thread.run();
}
}
PS:一般在实际开发中,选第2种。因为java只允许单继承。而实现则增加程序的健壮性,代码可以共享,代码和数据相对独立
3.使用匿名内部类
public class MyThread {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
thread.start();
}
}
4.Lambda表达式
public class Lambda {
public static void main(String[] args) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName());
}).start();
}
}
5.线程池
public class ThreadPool {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
}
线程的挂起与恢复
被废弃的方法
thread.suspend() :该方法不会释放线程所占用的资源。如果使用该方法将某个线程挂起,则可能会使其他等待资源的线程死锁
thread.resume(): 方法本身并无问题,但是不能独立于suspend()方法存在
可以使用的方法
wait(): 暂停执行、放弃已经获得的锁、进入等待状态
notify() :随机唤醒一个在等待锁的线程
notifyAll() :唤醒所有在等待锁的线程,自行抢占cpu资源
线程的优先级
线程的优先级设置可以为1-10的任一数值,Thread类中定义了三个线程优先级。
MIN_PRIORITY(1)
NORM_PRIORITY(5)
MAX_PRIORITY(10)