多线程控制

线程控制

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);
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值