线程控制
static void sleep(long millis):使当前正在执行的线程停留(暂停执行)指定的毫秒数。
package ThreadTest;
public class ThreadSleep extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(i);
try {
Thread.sleep(1000);//每隔一秒执行一次
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadSleep threadSleep1=new ThreadSleep();
ThreadSleep threadSleep2=new ThreadSleep();
ThreadSleep threadSleep3=new ThreadSleep();
threadSleep1.setName("孙权");
threadSleep2.setName("曹操");
threadSleep3.setName("刘备");
threadSleep1.start();
threadSleep2.start();
threadSleep3.start();
}
}
void jion():等待这个线程死亡。
package ThreadTest;
public class ThreadJoin extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(i+":"+getName());
}
}
public static void main(String[] args) {
ThreadJoin threadJoin1=new ThreadJoin();
ThreadJoin threadJoin2=new ThreadJoin();
ThreadJoin threadJoin3=new ThreadJoin();
threadJoin1.setName("康熙");
threadJoin2.setName("四阿哥");
threadJoin3.setName("八阿哥");
threadJoin1.start();
try {
threadJoin1.join();//调用join方法,等待线程死亡
} catch (InterruptedException e) {
e.printStackTrace();
}
threadJoin2.start();
threadJoin3.start();
}
}
只有当threadjoin1线程执行完毕,此线程死亡以后才会执行其他线程
void setDaemon(boolean on):将此线程标记为守护线程,当主线程运行完,只剩下守护线程之后,java虚拟机将会退出。
package ThreadTest;
public class ThreadDaemon extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName()+":"+i);
}
}
public static void main(String[] args) {
ThreadDaemon threadDaemon1=new ThreadDaemon();
ThreadDaemon threadDaemon2=new ThreadDaemon();
threadDaemon1.setName("守护线程1");
threadDaemon2.setName("守护线程2");
threadDaemon1.setDaemon(true);//设置守护线程
threadDaemon2.setDaemon(true);
threadDaemon1.start();
threadDaemon2.start();
Thread.currentThread().setName("主线程"); //设置主线程
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
当主线程执行完毕后,守护线程不久后停止执行。
主线程: for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}