线程的加入:
执行该语句的线程必须要让步给新加入的线程先完成任务,然后才能继续执行。
格式:以加入A线程为例
线程对象B.join() :无参数,则A线程一直暂停,直到B线程运行结束。
线程对象B.join(时间t) 有参数,则A线程每隔t时间暂停一次,直到B线程运行结束。
while(true)作为无限循环,经常在不知道循环次数的时候使用,并且需要在循环内使用break才会停止。
举例:
访问没前进一点,进度就跟进一点。
实现代码示例:
class TTT1 implements Runnable{
@Override
public void run() {
while (true){
System.out.println (Thread.currentThread ().getName ());//Thread.currentThread ()获得当前线程的引用。
}
}
}
public class jointest {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread (new TTT1 ());
t.start ();
t.join (2000);
while (true){
System.out.println (Thread.currentThread ().getName ());
}
}
}
执行默认线程2s后执行主线程。
线程优先级:
- 最大优先级:t1.setPriority( Thread.MAX_PRIORITY )
- 最小优先级:t2.setPriority( Thread.MIN_PRIORITY );
- 普通优先级:t3.setPriority( Thread.NORM_PRIORITY );
实现代码:
class TS implements Runnable{
@Override
public void run() {
while (true){
System.out.println (Thread.currentThread ().getName ());
}
}
}
public class 优先级 {
public static void main(String[] args) {
Thread t1 = new Thread (new TS(),"A");
Thread t2 = new Thread (new TS(),"B");
Thread t3 = new Thread (new TS(),"C");
t1.setPriority (Thread.MAX_PRIORITY);
t2.setPriority (Thread.MIN_PRIORITY);
t3.setPriority (Thread.NORM_PRIORITY);
t1.start ();
t2.start ();
t3.start ();
}
}
系统会优先执行A线程,然后是C,最后是B,这很好理解
线程中断:
java刚出来的时候存在几种的杀死线程的方法:
- t1.stop ();//杀死线程,不安全
- t1.suspend ();//存在死锁现象,所以被取消使用了
- t1.resume ();//存在死锁现象,所以被取消使用
上面的三种方法现在已经取消了,流行的是t.interrupt ();
代码实现:
class TTTT extends Thread {
@Override
public void run() {
try {
while (true) {
System.out.println (this.isInterrupted ());//是不是中断。
if (this.isInterrupted ()) {//Interrupted ()是一种状态
break;
}
System.out.println (Thread.currentThread ().getName ());
}
} catch (Exception e) {
e.printStackTrace ();
}
}
}
public class 中断 {
public static void main(String[] args) {
TTTT t = new TTTT ();
t.start ();
long tt = System.currentTimeMillis ();
while (System.currentTimeMillis () < tt + 10000) ;
t.interrupt ();
}
}
守护线程:
t.setDaemon(true)叫作守护线程,也叫精灵线程。守护线程可无线循环执行的且守护线程如果是由主线程启动的,当主线程执行完了,守护线程也就执行结束了。也就是说,只要是哪个线程启动守护线程的,守护线程就等待哪个线程的执行。
如果不是主线程启动的,只要主线程一结束,尽管守护线程守护的不是主线程,但是守护线程也就结束了。
守护线程往往是给主线程扫除障碍的,比如服务器的面临可能会崩溃的情况,守护线程会替主线程监视服务器的运行情况。
class TSS implements Runnable{
@Override
public void run() {
while (true){
System.out.println (Thread.currentThread ().getName ());
}
}
}
public class 守护线程 {
public static void main(String[] args) {
Thread t1 = new Thread (new TSS());
t1.setDaemon (true);//守护线程,当循环结束时,守护也结束了,true是设置守护线程,false是不守护
t1.start ();
for (int i = 0;i < 1000;i++){
System.out.println (Thread.currentThread ().getName ());
}
}
}