------- android培训、java培训、期待与您交流! ----------
JDK1.5中提供了多线程升级解决方案:
将同步synchronized替换成显示Lock操作
将Object中的wait,notify,notifyAll替换成了Condition对象
该对象可以通过Lock锁进行获取。
一个锁可以对应多个condition
在生产者消费者实例中实现了本方只唤醒对方的操作。
private Lock lock= new ReentrantLock();
private Condition condition_pro=lock.newCondition();
private Condition condition_con=lock.newCondition();
public void set(String name) throws InterruptedException
{
lock.lock();
try
{
while(flag)
condition_pro.await();
this.name=name+"..."+count++;
System.out.println(Thread.currentThread().getNmae()+"生产者"+this.name);
flag=true;
condition_con.signal();//对方对象调用唤醒
}
//finally最后释放锁
finally
{
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最后释放锁
finally
{
lock.unlock();
}
}
线程停止
stop方法已经过时
那么如何停止线程?
只有一种,run方法结束
开启多线程运行,运行代码通常是循环结构
只要控制住循环就可以让run方法结束,也就是结束线程
特殊情况:
当线程处于了冻结状态
就不会读取到标记,那么线程就不会结束
Thread类提供了interrupt();可以强制让线程回复到运行状态钟来 这样就可以操作标记让线程停下来
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");
flag=false;//通过interrupt()强迫线程运行状态后通过操作标记来停止线程
}
System.out.println(Thread.currentThread().getName()+"...run");
}
}
public void changeFlag()
{
flag=false;
}
}
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)
{
t1.interrupt();
t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName()+"..."+num);
}
System.out.println("over");
}
}
t1.steDeamon(true);//将线程设置成守护线程:主程序停止则线程停止
t1.join();//此线程要CPU执行权,可用于线程加入运行。
t1.setPriority(Thread.MAX_PRIORITY);//设置线程优先级
线程一般怎么写?
用匿名内部类的方法
class ThreadTest
{
public static void main(String[] args)
{
//一种写法
new Thread()
{
public void run()
{
for(int x=0;x<100;x++)
{
System.out.println(Thread.currentThread().getName()+"......"+x);
}
}
}.start
for(int x=0;x<100;x++)
{
System.out.println(Thread.currentThread().getName()+"......"+x);
}
//另一种方法
Runnable r=new Runnable()
{
public void run()
{
for(int x=0;x<100;x++)
{
System.out.println(Thread.currentThread().getName()+"......"+x);
}
}
};//匿名内部类
new Thread(r).start()
}
}