Java-多线程

马老师的讲解帮助我很好的把理论和实践代码联系起来了。

原则:多线程能使用接口就不使用继承— 灵活。。。。

public class TestThread1{
  public static void main(String args[])
{
    Runner1 r = new Runner1();
   // Thread t = new Thread(r);
    t.start();

    for(int i=0;i<100;i++)
    {  
    System.out.println("Main Thread:---"+i);
     }
 }
}
class Runner1 extends Thread{
//class Runner1 implements Runnable{
  public void extends Thread{
    for(int i=0;i<100;i++)
    {
    System.out.println("Runner1:"+i);
     }
}
}

sleep方法

·可以调用Thread的静态方法:
public static void sleep(long millis)throws
使得当前线程休眠(暂时停止执行millis毫秒)
·由于是静态方法,sleep可以有类名直接调用:
Thread.sleep(…)

public class TestInterrupt{
    public static void main(String[] args){
        MyThread thread = new MyThread();
        thread.start();
        try{InterruptedException e} ()
        thread.interrupt();//停止线程。泼凉水
    }
}

class MyThred extends Thread{
    public void run(){
        while(true){
            System.out.println("=="+new Date()+"==");
            try{
                sleep(1000);
            }catch(InterruptedException e){
                return;
            }

        }
    }
}

yield方法

·让出CPU,给其他线程执行的机会

public class TestYield{
    public static void main(String[] args){
        MyThread3 t1 = new MyThread3("t1");
        MyThread3 t2 = new MyThread3("t2");
        t1.start(); t2.start();
    }
}

class MyThread3 extends Thread {
    MyThread3(String s) {super(s);}
    public void run(){
        for(int i = 1;i<=100;i++){
            System.out.println(getName()+":"+i);
            if(i%10==0){
                yield();
            }
        }
    }
}

锁 synchronized

public class TestSycn implenents Runnable{
    Timer timer = new Timer();
    public static void main(String[] args){
        TestSync test = new TestSync();
        Thread t1 = new Thread(test);
        Thread t2 = new Thread(test);
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        t2.start();
    }
    public void run(){
        timer.add(Thread.currentThread().getName());
    }
}

class Timer{
    private static int num = 0;
    public synchronized void add(String name){
    //synchroized(this){
        num ++;
        try {Thread.sleep(1);}
        catch(InterruptedException e){}
        System.out.println(name+",你是第"+num+"个使用timer的线程");
    //}
    }
}


输出结果: t1,你是第2个使用timer的线程
         t2,,你是第2个使用timer的线程
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 20
    评论
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值