JDK1.5中提供了多线程升级解决方案。
将同步Synchronized替换为显示的Lock操作;将Object中的wait,notify,notifyAll替换为Condition对象,该对象可以通过Lock锁进行获取。
实例代码:
import java.util.concurrent.locks.*;
public class ProducerConsumerDemo{
public static void main(String[] args){
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource{
private String name;
private int count = 1;
private boolean flag = false;
private Lock lock = new ReentrantLock(); //新建锁
private Condition condition_pro = lock.newCondition(); //condition绑定Lock
private Condition condition_con = lock.newCondition(); //1个lock可以绑定多个condition
public void set(String name)throws InterruptedException{
lock.lock(); //Lock的lock方法,加锁,替换synchronized
try{
while(flag)
condition_pro.await();
this.name = name +"--"+count++;
System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
flag = true;
condition_con.signal();
}
finally{
lock.unlock(); //Lock的unlock方法,释放锁
}
}
public void out()throws InterruptedException{
lock.lock();
try{
while(!flag)
condition_con.await();
System.out.println(Thread.currentThread().getName()+"...消费者......."+this.name);
flag = false;
condition_pro.signal();
}
finally{
lock.unlock();
}
}
}
class Producer implements Runnable{
private Resource res;
Producer(Resource res){
this.res = res;
}
public void run(){
while(true){
try{
res.set("+商品+");
}
catch(InterruptedException e){
}
}
}
}
class Consumer implements Runnable{
private Resource res;
Consumer(Resource res){
this.res = res;
}
public void run(){
while(true){
try{
res.out();
}
catch(InterruptedException e){
}
}
}
}
----------------------------------------------------------------------------------------------------------------
停止线程:
stop()方法已经过时,不允许再被使用。
如何停止线程?只有一种,run方法结束。
开启多线程运行,运行代码通常是循环结构。所以只要控制循环,就可以让run方法结束,也就是线程结束。
特殊情况:当线程处于了冻结状态,就不会读取到标记,那么线程就不会结束。
例如代码如下:
class StopThread implements Runnable{
private boolean flag = true;
public synchronized void run(){
while(flag){
try{
wait();
}
catch(InterruptedException e){
System.out.println(Thread.currentThread().getName()+"....Exception");
}
System.out.println(Thread.currentThread().getName()+"....run");
}
}
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();
break;
}
System.out.println(Thread.currentThread().getName()+"........"+num);
}
}
}
结果为:
程序没有结束,必须按ctrl+c强制结束。
interrupt方法是强制清除线程的冻结状态,恢复到运行状态,而不是结束线程。