您的位置:首页 > 其它

多线程3

2015-08-06 16:29 246 查看
1、wait和sleep的区别

①wait可以指定时间,也可以不指定时间。sleep必须指定时间,因为sleep可以不需要别人唤醒,可以自己醒过来。

②sleep释放执行权,释放锁。wait释放执行权,不释放锁。

2、停止线程的方式

①通过在run方法中定义标志位的形式,判断标志位的改变,来结束进程

class StopThread implements Runnable
{
private boolean flag = true;
public synchronized void run()
{
while(flag)
{
System.out.println(Thread.currentThread().getName()+"......++++");
}
}
public void setFlag()
{
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.setDaemon(true);
t2.start();

int num = 1;
for(;;)
{
if(++num==50)
{
st.setFlag();
break;
}
System.out.println("main...."+num);
}

System.out.println("over");
}
}
通过在循环中判断flag的值来确定是否结束线程。

②当线程冻结时,无法判断标志位flag,无法继续执行线程。这时可以用interrupt方法来将线程强制从冻结状态恢复到运行状态来,让线程具备CPU的执行资格。强制动作会发生InterruptedException异常,需要处理。

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()+"....."+e);
flag = false;
}

System.out.println(Thread.currentThread().getName()+"......++++");
}
}
public void setFlag()
{
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.setDaemon(true);
t2.start();
int num = 1;
for(;;)
{
if(++num==50)
{
t1.interrupt();
break;
}
System.out.println("main...."+num);
}
System.out.println("over");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: