线程

来源:互联网 发布:校园谈论源码 编辑:程序博客网 时间:2024/05/01 21:09

一、线程概念

一个程序里面不同的执行路径。

注:一个cpu在同一时间点只能执行一个线程,因其速度非常快所以感觉在通知执行多个任务。

二、线程的状态

new 创建

start 就绪(等待cpu分配执行片段)

阻塞

结束

线程的状态转换

三、线程常用方法

1、sleep();

线程睡眠,并没有释放锁。属于Thread的方法,需要捕获InterruptedException异常

2、yield();

暂时让出线程,给其他线程执行会

3、join();

执行当前线程至到结束再将cpu让出给其他线程,需要捕获InterruptedException异常

4、Priority();

线程优先级

5、wait();

暂停线程,放弃当前线程锁,属于object对象方法

6、synchronized

线程加锁

7、notify();

唤醒等待执行的线程

notifyAll();

唤醒所有等待执行的线程

四、创建线程的方法

1、继承Thread类

2、实现Runable接口

能实现接口就不要用继承类,因为接口比较灵活。

五、wait与sleep的区别

wait属于object类的方法,wait将当前线程锁释放

sleep属于Thread方法,sleep并未释放当前锁

六、线程与进程区别

线程是一个程序里面不同的执行路径;

与进程的区别

(1)地址空间:进程内的一个执行单元;进程至少有一个线程;它们共享进程的地址空间;而进程有自己独立的地址空间;
(2)资源拥有:进程是资源分配和拥有的单位,同一个进程内的线程共享进程的资源
(3)线程是处理器调度的基本单位,但进程不是

七、线程同步经典案例——生产者消费者

public class Mantou {

int id;

Mantou(int id) {
this.id = id;
}

public String toString() {
return "馒头编号:" + id;
}

}

/**
 * 篮子(堆栈)容器
 * 
 * @author Administrator
 */
public class SyncStack {

int index = 0;
Mantou[] array = new Mantou[5];
/**
* 生产馒头
* @param mantou
*/
public synchronized void push(Mantou mantou) {
if (index == array.length) {// 堆栈满了
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.notify();
array[index] = mantou;
index++;
}
/**
* 吃馒头
* @param mantou
*/
public synchronized Mantou pop() {
if (index == 0) {// 堆栈空了
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.notify();
index--;
return array[index];
}


}

/**
 * 馒头生产者
 * @author Administrator
 *
 */
public class Producer implements Runnable{

    SyncStack ss = null;
    Producer(SyncStack ss){
    this.ss =  ss;
    }
public void run() {
for(int i = 0; i < 20 ;i++){
Mantou mantou = new Mantou(i);
ss.push(mantou);
System.out.println("生产了馒头:" + mantou);
}
}
   
}

/**
 * 馒头消费者
 * @author Administrator
 *
 */
public class Consumer implements Runnable{

    SyncStack ss = null;
    Consumer(SyncStack ss){
    this.ss =  ss;
    }
    public void run() {
    for(int i = 0; i < 20 ;i++){
    Mantou mantou = ss.pop();
    System.out.println("吃了馒头:"+mantou);
    }
    }


}

public class ThreadTest {

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();
}


}

0 0
原创粉丝点击