Java基础6

等待唤醒机制---->生产消费问题

/**

*

* @author Jinyan

*

*/

class ResourceProducers

{

private String name;

private int count = 1;

private boolean flagduck = false;

public synchronized void set(String name)

{

while(flagduck)

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

this.name = name + count;

count ++;

System.out.println(Thread.currentThread().getName()

+"--producer-->"+this.name);

flagduck = true;

this.notifyAll();

}

public synchronized void out()

{

while(!flagduck)

//if判断标记,只运行一次,会导致不改运行的线程运行了,

也导致了数据错误的情况

//while判断标记,解决了线程获取执行后,是否要运行

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println(Thread.currentThread().getName()

+"--consumer-->"+this.name);

flagduck = false;

this.notifyAll();

//notify()只能唤醒一个线程,如果唤醒了本方线程,

而while判断notify会导致死锁

//notifyAll()解决了,本方线程一定会唤醒对方线程

}

}

class Producer implements Runnable

{

private ResourceProducers rp = new ResourceProducers();

Producer(ResourceProducers rp)

{

this.rp = rp;

}

public void run()

{

while(true)

{

rp.set("Duck");

}

}

}

class Consumer implements Runnable

{

private ResourceProducers rp = new ResourceProducers();

Consumer(ResourceProducers rp)

{

this.rp = rp;

}

public void run()

{

while(true)

{

rp.out();

}

}

}

class ProducerConsumerDemo {

public static void main(String[] args) {

ResourceProducers rp = new ResourceProducers();

Producer p = new Producer(rp);

Consumer c = new Consumer(rp);

Thread t0 = new Thread(p,"脔割");

Thread t1 = new Thread(p,"儿纸");

Thread t2 = new Thread(c,"弟鸽");

Thread t3 = new Thread(c,"办证");

t0.start();

t1.start();

t2.start();

t3.start();

}

}

通过锁对象完成同步

wait和sleep的区别

1.wait可以指定时间也可以不指定

sleep必须指定时间

2.在同步中时,对cpu的执行权和锁的处理不同

wait: 释放执行权,释放锁

sleep:释放执行权,不释放锁

线程的停止

1.stop()

2.run()方法结束

怎么控制线程任务的结束--->通过循环结构控制

定义标记来完成

当线程处于冻结状态时,无法读取标记,此时应该如何停止线程?

interrupt()方法将线程从冻结状态强制恢复到运行状态,

让线程具备cpu的运行资格

但是会发生异常 InterruptedException

join(); 运行至本线程结束

clss Test implements Runnable

{

public void run(Thread t)

{}

}//代码有错吗?

有 错误在第一行 应该被abstract修饰

class ThreadTest

{

public static void public static void main(String[] args) {

new Thread(new Runnable()

{

public void run()

{

System.out.println(Runnable);

}

})

{

public void run()

{

System.out.println(Thread);

}

}.start();

}

}

你可能感兴趣的:(Java基础6)