Java多线程、IO流

java多线程

01-多线程的引入

定义:同时对多项任务加以控制。(例如,可以边听音乐边吃饭)

02-多线程的实现

方法1继承Thread类


public class Test extends Thread
{
   
   private String ThreadName;
   private int baozi=1;
   public String get()
   {
   
       return this.ThreadName;
   }
   public void set(String ThreadName)
   {
   
       this.ThreadName=ThreadName;
   }
   public Test(String ThreadName)
   {
   
    super();
    this.ThreadName=ThreadName;
   }

   public void run ()
   {
   
       while(baozi<10)
       {
   
           System.out.println(ThreadName+"吃第"+baozi+"个包子");
           baozi++;
       }
   }
   public static void main(String[] args) 
    {
   
        Test t1=new Test("张三");
        Test t2=new Test("李四");
        t1.start();
        t2.start();

       //结果,张三李四一起执行
    }
}

方法2Runnable接口中的run方法

public class Test implements Runnable
{
   
   private String ThreadName;
   private int baozi=1;
   public String get()
   {
   
       return this.ThreadName;
   }
   public void Tset(String ThreadName)
   {
   
       this.ThreadName=ThreadName;
   }
   public Test(String ThreadName)
   {
   
    super();
    this.ThreadName=ThreadName;
   }

   public void run ()
   {
   
       while(baozi<10)
       {
   
           System.out.println(ThreadName+"吃第"+baozi+"个包子");
           baozi++;
       }
   }
   public static void main(String[] args) 
    {
   
        Test t1=new Test("张三");
        Test t2=new Test("李四");
       
       //和上面的写法不同
       //t1,t2只是实现了接口的普通类
        Thread t11=new Thread(t1);
        Thread t12=new Thread(t2);
		t11.start();
       	t12.start();
       //结果,张三李四一起执行
    }
}

利用Thread类可以节约资源

Test t1=new Test("超级张三");
Thread t11=new Thread(t1);
Thread t12=new Thread(
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值