进程线程
进程:运行中的程序
线程:进程创建的
单线程:同一时刻,只能执行一个线程
多线程:同一时刻,能执行多个线程
并发:同一时刻,多个任务交替执行,造成同时执行的错觉,简单就是单核CPU实现的多任务就是并发
并行:同一时刻,多个任务同时执行,多核CPU可以实现并发并行
Runtime runtime = Runtime.getRuntime();
int i = runtime.availableProcessors();
线程基本使用
继承Thread类 重写 run 方法
继承runnable接口 重写 run 方法 (静态代理)
public static void main(String[] args) {
hello hello = new hello();
hello.start();
new Thread(new hello2()).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello3");
}
}).start();
}
class hello extends Thread{
@Override
public void run() {
System.out.println("hello");
}
}
class hello2 implements Runnable{
@Override
public void run() {
System.out.println("hello2");
}
}
静态代理模式
public static void main(String[] args) {
new proxy(new A()).start();
}
class A implements Runnable{
@Override
public void run() {
System.out.println("HAHA");
}
}
class proxy implements Runnable{
private Runnable target = null;
@Override
public void run() {
if(null != target){
target.run();
}
}
public proxy(Runnable target) {
this.target = target;
}
public void start(){
start0();
}
private void start0() {
run();
}
}
方法
yield-->线程礼让 不一定礼让成功
join-->线程插队,插队一旦成功,肯定先执行玩插入线程的所有任务。
setDaemon() 设置成守护进程 随着用户线程结束 退出
线程的生命周期
public enum State {
NEW,
RUNNABLE, //ready running
BLOCKED,
WAITING,
TIMED_WAITING,
TERMINATED;
}
互斥锁
synchronized
在使用synchronized时注意:
1.同步方法(非静态的)的锁可以是this也可以是其他对象,要求是同一对象
2.同步方法(静态的)的锁为当前类的本身。
public class A {
Object object = new Object();
public void m(){
synchronized (object){
}
synchronized (this){
}
}
public static void n(){
synchronized (A.class){
}
}
}