极客学院java 线程代码笔记1


//java 线程实现的两种方法:
//方法一:继承Thread类 ,方法二:实现Runnable接口


class Mythread extends Thread{

    String name;      //储存线程名字

    Mythread(String name){
        this.name=name;
    }

    public void run(){         //覆盖run();

        for(int i=0;i<1011;i++){
            System.out.println(name+":"+i);      //方便观察
        }
        super.run();
    }
}


//方法二:(推荐使用)
class Myrunnable implements Runnable{

    String name;
    Myrunnable (String name){
        this.name=name;
    }
    public void run(){
        for(int i=0;i<1000;i++){
            try {
                Thread.sleep(1000);  //每秒执行一次
                System.out.println(name+":"+i);
              //System.out.println("当掐线程对象:"+Thread.currentThread().getName());
                if(i==10){
                    System.out.println("线程礼让:");
                    Thread.yield();          //让另一线程执行
                }

            } catch (InterruptedException e) {              
                e.printStackTrace();
            }       
        }
    }

}


public class ThreadDemo {

    public static void main(String[] args) {
        /*
        Mythread p1=new Mythread("p1");
        Mythread p2=new Mythread("p2");       //构造两个线程,方法一
        p1.start();
        p2.start();             //用start()启动而不是run();
        System.out.println();
        */
        Myrunnable p3=new Myrunnable("p3");  //方法二
        Myrunnable p4=new Myrunnable("p4");
        Thread t3=new Thread(p3);
        Thread t4=new Thread(p4);
        System.out.println(t3.isAlive());     //判断是否启动
        t3.start();
        for(int i=0;i<100;i++)
        {
            if(i>10){
                try {
                    t4.join();             //强行加入线程
                    System.out.println("新加入线程t4");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("主线程正在执行");
        }



    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值