---------------------- android培訓、java培訓、期待與您交流! ---------------------
1. JDK5.0實現生產者消費者模型:
public class ProducterConsumer {
public static void main(String[] args) {
Goods goods=new Goods();
Producter pro=new Producter(goods);
Consumer con=new Consumer(goods);
new Thread(pro).start();
new Thread(con).start();
new Thread(pro).start();
new Thread(con).start();
}
}
class Goods{
String name;
int count=0;
Lock lock=new ReentrantLock();
Condition conSetter=lock.newCondition();
Condition conGetter=lock.newCondition();
boolean flag=false;
public void getName() {
lock.lock();
try{
while(!flag)
try {
conGetter.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"~~~消費者~~~~"+name+" "+count);
flag=false;
conSetter.signalAll();
}finally{
lock.unlock();
}
}
public void setName(String name) {
lock.lock();
try{
while(flag)
try {
conSetter.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
this.name=name;
count++;
System.out.println(Thread.currentThread().getName()+"~~~~~~生產者~~~~~~~~~"+name+" "+count);
flag=true;
conGetter.signalAll();
}finally{
lock.unlock();
}
}
}
class Consumer implements Runnable{
Goods goods=new Goods();
public Consumer(Goods goods) {
this.goods=goods;
}
@Override
public void run() {
while(true)
goods.getName();
}
}
class Producter implements Runnable{
Goods goods=new Goods();
public Producter(Goods goods) {
this.goods=goods;
}
@Override
public void run() {
while(true)
goods.setName("商品");
}
}
10.停止線程:stop方法已經過時,不能用它停止線程。由於多線運行代碼通常是循環結構因此,要停止線程時,可以用標記控制線程,使run方法結束。
特殊情況:
當線程處於了凍結狀態,即等待狀態時,就不會讀取到標記。那麼線程就不會結束。此時,可以用Thread類提供該方法 interrupt()方法強制讓線程恢復到運行狀態中來。這樣就可以操作標記讓線程結束。
class StopThread implements Runnable
{
private boolean flag =true;
public void run()
{
while(flag)
{
try {
Thread.sleep(1111111);
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName()+"....run");
}
System.out.println(Thread.currentThread().getName()+"....over");
}
public void changeFlag()
{
flag = false;
}
}
public class StopThreadDemo
{
public static void main(String[] args)
{
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.start();
int num = 0;
while(true)
{
if(num++ == 60)
{
st.changeFlag();
//若沒有此段代碼,線程要等到睡眠時間結束後纔會結束
t1.interrupt();
t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName()+"......."+num);
}
System.out.println("over");
}
}
11.當在主線程中調用d.join()方法時(d爲線程),d線程將會搶奪主線程的cup,此時將執行d線程,主線程處於阻塞狀態,直到d線程執行完爲止。
---------------------- android培訓、java培訓、期待與您交流! ----------------------