1、守护线程
代码如下:
import java.util.concurrent.locks.*;
public class StopTest implements Runnable
{
private boolean flag=true;
private Lock lock=new ReentrantLock();
private Condition c=lock.newCondition();
public void run()
{
while(flag)
{
lock.lock();
try{Thread.sleep(200);} //睡眠冻结,将sleep中的时间通过不断的调整,可以得到不同的结果!
catch(Exception e){System.out.println(Thread.currentThread().getName()+"....Sleep");}
try{c.await();} //等待冻结
catch(InterruptedException e){System.out.println(Thread.currentThread().getName()+".....Exception");}
System.out.println("...."+Thread.currentThread().getName());
lock.unlock();
}
}
public void changeFlag()
{
flag=false;
}
}
public class StopDemo
{
public static void main(String[] args)
{
int i=0;
StopTest t=new StopTest();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
t1.setDaemon(true); //将t1设置为守护线程
t2.setDaemon(true); //将t2设置为守护线程
t1.start();
t2.start();
while(true)
{
try{Thread.sleep(10);}catch(Exception e){}
if(i++==10)
{
t.changeFlag();
//t1.interrupt(); //t1唤醒
//t2.interrupt(); //t2唤醒
break;
}
System.out.println(Thread.currentThread().getName()+"..."+i);
}
try{Thread.sleep(1);}catch(Exception e){}
//t1.interrupt(); //t1唤醒
//t2.interrupt(); //t2唤醒
System.out.println("over");
}
}
2、join方法
当A线程执行到了B线程的执行方法时,A线程就会等待,等B线程都执行完后,A才会执行!!
2.1、如在主线程中:t1.start();
t1.join();
t2.start();
主线程碰到t1.join();,则主线程冻结,将执行权交给t1,由于主线程运行不到 t2.start();,则只有t1有执行权!
2.1、如在主线程中:t1.start();
t2.start();
t1.join();
主线程碰到t1.join();,则主线程冻结,将执行权交给t1,由于主线程已经运行t2.start();,则t1与t2均有执行权,两个线程可以交替执行,但是如果t1线程结束,则主线程从冻结状态恢复(不管t2线程结束与否)!
3、yeld方法
4、设置线程优先级setPriority
更改线程的优先级。