1进程和线程:
1个exe是一个进程,线程是里面运行的子任务,有了多线程,才有了多任务的并行执行
2多线程的实现方式:
Runnable接口和Thread类,同时Thread implements Runnable ,两种方式都可以
3一个线程类,针对实例变量就会有共享与不共享之分,线程间的交互就存在线程安全问题。
是否共享,看你怎么用,如果把同一个Thread类,传给多个thread类去继承,那这些子类自然是拥有父类中的定义变量,此时就是共享了,关于线程安全问题,每个线程类都势必要实现run方法,要想run方法执行时不要多个线程都进入,就要在这个方法上加锁,关键字是synchronized,不止这个方法,只要不允许同时进入的地方,就要加锁
4关于System.out.println("i="+(i--))异常问题
sysout方法本身是加锁的,内部同步,但这里i--是在进入println方法之前进入的,所以这样操作时就错在一个线程安全问题
5 currentThread()方法
Thread.currentThread().getName(),关于这个方法调用的结果指向,跟调用的位置,调用者是谁有关
如果是在MyThread的构造函数里调用,那这个构造函数在哪里调用这里指向就是谁,在main方法里调用了MyThread的构造函数,这里就指向main (这个main是指的main主线程,不是main函数,只是同名而已)
如果是在MyThread的run方法里调用,MyThread的实例mythread.start() 这里内部调用的run,实际调用者就是mythread对应的线程Thread-0,所以这里指向是Thread-0
如果是在MyThread的run方法里调用,MyThread的实例mythread.run() 这里直接调用的run,实际调用者就是main
6关于this的指向,是当前类
public class TestThread extends Thread{
System.out.println("constructor currentThread:"+Thread.currentThread().getName()+ " "+Thread.currentThread().getId());
//this.currentThread().getName() 这个写法不推荐了,建议直接是Thread
System.out.println("constructor this:"+this.getName()+" "+this.getId());
//这个方法就是返回线程名,非线程类没有这个方法
}
public void run(){
System.out.println("run currentThread:"+Thread.currentThread().getName()+" "+Thread.currentThread().getId());
System.out.println("run this:"+this.getName()+" "+this.getId());
}
public static void main(String[] args) {
TestThread thread = new TestThread();//constructor currentThread:main 1
//constructor this:Thread-0 9
Thread thread2 = new Thread(thread);
thread2.setName("aa");
thread2.start();//run currentThread:aa 10 run this:Thread-0 9
//thread2.run();//run currentThread:main 1 run this:Thread-0 9
}
}
start启动和run启动的区别:
1start方法启动,调用者是thread-0自身,run方法启动,调用者是main
7 sleep方法是让当前正在执行的线程休眠,暂停执行
Thread.sleep(2000)//调用者是谁,thread就指向谁
8isAlive()判断当前线程是否处于活跃状态,自定义线程是否已启动run,start,是否执行完成,当前线程是主线程main,还是自定义线程
9 停止线程:
Thread.stop()不建议使用,已过时,且不安全
Thread.interrupt() 此方法不会终止,还需要加个判断
停止线程的方法有:
- 退出标志,使线程正常退出,run后终止;
- stop强行退出,不建议,和suspend,resume一样过期作废 且不安全
- interrupt中断线程 ,此方法不会终止,只是加了个停止标记,还需要加个判断
关于interrupt方法:
判断是否停止的方法:
this.interrupted() 测试当前线程是否已经是中断状态,执行后具有将标记状态清楚为false的功能
this.isInterrpted()测试线程Thread对象是否已经中断状态,但不清除状态标志