1、线程是一个程序内部不同的执行路径
2、生成线程只要能使用接口就不要继承,继承后就不能继承其他的类,比较死。而且继承的run方法不能抛出与父类不同的异常。比如sleep的IntterruptedException
3、start方法只是说我准备好了,进入就绪状态了,等待调度后才进入运行状态
4、线程控制基本方法
5、线程关闭
1)thread.interrupt 让线程中断,还可以在InterruptException里做其他处理
2)stop已经废弃了,比interrupt还粗暴
3)通过标志flag不满足条件关闭run方法,run方法结束,线程结束
6、线程同步
public class T implements Runnable{ int b = 100; public synchronized void m1() throws Exception{ b = 1000; Thread.sleep(5000); System.out.println("b = " + b); } public synchronized void m2() throws InterruptedException { Thread.sleep(2500); b = 2000; } public void run(){ try { m1(); }catch (Exception e){ e.printStackTrace(); } } public static void main(String[] args) throws Exception{ T t = new T(); Thread t1 = new Thread(t); t1.start(); Thread.sleep(1000); t.m2(); } }
结果
b = 1000
如果m2方法去掉synchronized 则输出b=2000,原因是如果加了synchronized 则表示需要等锁,但是如果没有加锁的方法是可以直接访问的。
7、生产者消费者
public class ProducerConsumer { public static void main(String[] args) { SyncStack ss = new SyncStack(); Producer p = new Producer(ss); Consumer c = new Consumer(ss); new Thread(p).start(); new Thread(c).start(); System.out.println(ss.index); } } class WoTou{ int id; WoTou(int id){ this.id = id; } public String toString(){ return "WoTou : "+ id; } } class SyncStack{ int index = 0; WoTou[] arrWT = new WoTou[6]; public synchronized void push(WoTou wt){ while(index == arrWT.length){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); arrWT[index] = wt; index++; } public synchronized WoTou pop(){ while(index == 0){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); index--; return arrWT[index]; } } class Producer implements Runnable{ SyncStack ss = null; Producer(SyncStack ss){ this.ss = ss; } public void run(){ for(int i=0;i<20;i++){ WoTou wt = new WoTou(i); ss.push(wt); System.out.println("生产了:"+wt); try { Thread.sleep((int) Math.random()*200); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Consumer implements Runnable{ SyncStack ss = null; Consumer(SyncStack ss){ this.ss = ss; } public void run(){ for(int i=0;i<20;i++){ WoTou wt = ss.pop(); System.out.println("消费了:"+ wt); try { Thread.sleep((int) Math.random()*1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(wt); } } }