版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lsf921016/article/details/62217107
一.实现runable接口创建线程的步骤:
- 定义类实现runable接口,
- 覆盖接口中的run方法,并将线程的任务代码写进run方法中
- 通过Thread类创建线程对象,并将runable接口的子类对象作为Thread类的构造函数进行传递。
4.调用线程对象的start方法开启线程。
class NewThread implements Runable{
public void run(){}
}
二.此方法较继承Thread类来创建线程的好处:
- 不必继承Thread类中的所有方法
- 避免了java单继承的局限性。
三 线程同步:
- 使用synchronized代码块,锁是object
- 使用synchronized同步函数,锁是this
- 静态的同步函数使用的锁 是该函数所属的字节码文件对象,可以getclass()获取。
四 线程间通信
多个线程处理同一个共享资源,但是任务不同
等待/唤醒机制
- wait():Object类的方法,让线程处于冻结状态(进入等待对象锁队列),被wait的线程会被存储到线程池中,释放cpu,释放锁。
- sleep():Thread类的方法,释放cpu,但是不释放锁。
- notify():Object类的方法,唤醒线程池中的一个线程(任意)。
*这些方法必须写在同步中
*必须明确操作的是哪个锁上的县城
五 实例:生产者消费者问题
package socket.MultiThread;
/**
* Created by lenovo on 2017/3/14.
*/
class Resource {
private String name;
int count;
boolean flag = false;
public synchronized void produce(String name) {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name + count;
++count;
System.out.println(Thread.currentThread().getName() + name+count + "+1");
flag = true;
notify();
}
public synchronized void consume() {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + name +count+ "-1");
flag = false;
notify();
}
}
class Producer implements Runnable {
Resource r;
public Producer(Resource r) {
this.r = r;
}
@Override
public void run() {
while (true) {
r.produce("烤鸭");
}
}
}
class Consumer implements Runnable {
Resource r;
public Consumer(Resource r) {
this.r = r;
}
@Override
public void run() {
while(true){
r.consume();
}
}
}
public class ProducerConsumer {
public static void main(String[] args) {
Resource r=new Resource();
Producer producer=new Producer(r);
Consumer consumer=new Consumer(r);
Thread t1=new Thread(producer);
Thread t2=new Thread(consumer);
t1.start();
t2.start();
}
}