多线程(一)多线程的实现

一.用继承方法实现多线程
 
public class MultiThread {
    public static void main(String[] args)
    {
        Th t=new Th();
        //t.setDaemon(true);    //定义为后台执行线程,当主线程结束,后台线程也结束;
        t.setPriority(Thread.MAX_PRIORITY);//也有MIN_PRIORITY,NONE_PRIORITY;
        t.start();             //线程开始执行
        int index=0;
        while (true )
        {
           
            if(index++==1000) //index的值增加,index++的值也增加
                break;
           
           
       
           System.out.println("main:"+Thread.currentThread().getName());
        }
    }
   
}
class Th extends Thread{
    public void run()
    {
        while(true)
        {
             System.out.println(getName()+"thread2");
       
             yield();   //放弃其执行的权利,让别的进程优先执行
        }
    }
   
}
注意:(1)定义优先级,java虚拟机并不是先只执行优先级高的程序,而不执行优先级低的程序,长时间被放置的优先级比较低的程序也可被执行;
(2)计算机在同一时刻只执行一个线程,但多线程交替执行;

二.用接口实现多线程实例:
 
public class MultiThread2 {
    public static void main(String[] args)
    {
      Thread2 t=new Thread2();
      new Thread(t).start();
      System.out.println(Thread.currentThread().getName());
    }
   

}
class Thread2 implements Runnable
{
    public void run()
    {
        System.out.println(Thread.currentThread().getName());
    }
}

优点:(1)用接口可以创建一个可以继承其他类的线程;
      (2)可以使主类中创建的进程拥有同一个变量;
















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值