一些基础的线程例子

1.建立线程的方式:继承Thread类和实现Runnable接口。下面这个例子是通过继承类的方式创建线程的。

  1. package mythread;  
  2.    
  3.  public class Thread1 extends Thread  
  4.   {  
  5.       public void run()  
  6.       {  
  7.           System.out.println(this.getName());  
  8.       }  
  9.       public static void main(String[] args)  
  10.       {  
  11.           System.out.println(Thread.currentThread().getName());  
  12.           Thread1 thread1 = new Thread1();  
  13.           Thread1 thread2 = new Thread1 ();  
  14.           thread1.start();  
  15.           thread2.start();  
  16.       }  
  17.   }

上面的代码建立了两个线程:thread1和thread2。上述代码中的005至008行是Thread1类的run方法。当在014和015行调用start方法时,系统会自动调用run方法。在007行使用this.getName()输出了当前线程的名字,由于在建立线程时并未指定线程名,因此,所输出的线程名是系统的默认值,也就是Thread-n的形式。在011行输出了主线程的线程名。

下面这个例子是通过实现Runnbale借口建立线程的

  • public class MyRunnable implements Runnable  
  • {  
  •     public void run()  
  •     {  
  •         System.out.println(Thread.currentThread().getName());  
  •     }  
  •     public static void main(String[] args)  
  •     {  
  •         MyRunnable t1 = new MyRunnable();  
  •         MyRunnable t2 = new MyRunnable();  
  •         Thread thread1 = new Thread(t1, "MyThread1");  
  •         Thread thread2 = new Thread(t2);  
  •         thread2.setName("MyThread2");  
  •         thread1.start();  
  •         thread2.start();  
  •     }  
  • }  

2.为每个线程取名字的方式:Thread类有一个重载构造方法可以设置线程名 和 使用Thread类的setName方法修改线程名。

  1. package mythread;  
  2.  
  3. public class Thread2 extends Thread  
  4. {  
  5.     private String who;  
  6.  
  7.     public void run()  
  8.     {  
  9.         System.out.println(who + ":" + this.getName());  
  10.     }  
  11.     public Thread2(String who)  
  12.     {  
  13.         super();  
  14.         this.who = who;  
  15.     }  
  16.     public Thread2(String who, String name)  
  17.     {  
  18.         super(name);  
  19.         this.who = who;  
  20.     }  
  21.     public static void main(String[] args)  
  22.     {  
  23.         Thread2 thread1 = new Thread2 ("thread1""MyThread1");  
  24.         Thread2 thread2 = new Thread2 ("thread2");  
  25.         Thread2 thread3 = new Thread2 ("thread3");  
  26.         thread2.setName("MyThread2");  
  27.         thread1.start();  
  28.         thread2.start();  
  29.         thread3.start();  
  30.     }  

在main方法中建立了三个线程:thread1、thread2和thread3。其中thread1通过构造方法来设置线程名,thread2通过setName方法来修改线程名,thread3未设置线程名。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值