Oracle培训(十三)——Core Java第十三章知识点总结——线程
Core Java第十三章知识点总结——线程
知识点预览
线程的概念
线程的开发
线程的状态
线程的同步
wait与notify
线程的概念
1. 线程的概念
在一个程序中同时运行的多个独立流程,每一个独立的流程就是一个线程。
2. 线程的三要素:CPU Code Data
3. 线程并发
同一时间对个线程同时执行
对个线程:轮流使用CPU,有先后顺序,
短暂时间:CPU时间片
人的反映时间远大于CPU时间片:认为线程同时执行
4. 主线程
main方法代表主线程
线程的开发
1.继承Thread类与实现Runnable接口两种方式
2. 继承Thread类开发线程
a) 用户定义一个类继承Thread类
b) 覆盖run方法
c) 运行线程//start 启动线程
3. 思考
2. sleep与阻塞
阻塞状态
3.sleep方法(Thread定义)
a) public static void sleep(longmillis) throws InterruptedException
// long millis:睡多少毫秒
// InterruptedException:检查异常
b) 利用sleep()方法对线程的控制是非常不精确的。
4.join方法
a)join方法法也会导致线程阻塞
b)特点:如果当前线程中调用了另外一个线程的join方法,当前线程会立即阻塞看,知道另外一个线程运行完成。
c) join方法的问题:
i. 如果2个线程调用对方的join方法会导致程序无法运行
ii. 解决办法:public final void join(long millis) throws InterruptedException
//重载方法
//参数为long类型往往代表毫秒
//不管是否运行完,阻塞------>可运行
线程同步
1. 应用数组实现一个栈
synchronized(this)(使用当前对象的互斥锁标志)
synchronized修饰方法(使用当前对象的互斥锁标志)
7. synchronized注意
a) 对象互斥锁标志是与对象挂钩的
package chp13.ex09;/** * * @Author: Wentasy * @FullName: TestProducerConsumer.java * @Description: 线程通信:生产者和消费者问题 * @Create Date: 2012-8-17 */public class TestProducerConsumer {public static void main(String[] args) {Stack s=new Stack();Thread t1=new Producer(s);Thread t2=new Consumer(s);t1.start();t2.start();}}class Stack{private char[] data=new char[6];private int index=0;private void print(){for(int i=0;i<index;i++){System.out.print(data[i]+" ");}System.out.println();}public synchronized void push(char c){while(index==data.length){try {this.wait();} catch (InterruptedException e) {}}data[index]=c;index++;this.notifyAll();System.out.print(c+" push stack:");print();}public synchronized void pop(){while(index==0){try {this.wait();} catch (InterruptedException e) {}}index--;char c=data[index];data[index]=' ';this.notifyAll();System.out.print(c+" poped stack:");print();}}class Producer extends Thread{Stack s;public Producer(Stack s) {this.s = s;}public void run(){for(char c='A';c<='Z';c++){s.push(c);try {Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}}}}class Consumer extends Thread{Stack s;public Consumer(Stack s) {this.s = s;}public void run(){for(int i=1;i<=26;i++){s.pop();try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}}}
栈满:不能加
栈空:不能弹