java多线程

亡梦爱人 提交于 2020-02-10 03:43:54
  • 两种实现方式:一、实现Runnable接口。二、继承Thread类。
  • 重写run()方法,调用start()方法。

 

一、实现Runnable接口
    class T implements Runnable{
              int a=0;
              String name;
              public T(String str) {
                     this.name=str;
              }
              
              @Override
              public void run() {
                     // TODO Auto-generated method stub
                     while(a<10) {
                           a++;
                           System.out.println(name+" :   "+a);
                     }
                     
              }      
       
}
public class Test{
       
       public static void main(String args[]) {
              
              T t1=new T("线程1");
              T t2=new T("线程2");
              Thread w1=new Thread(t1);
              Thread w2=new Thread(t2);
              w1.start();
              w2.start();
       }
}
 
二、继承Thread类
class T extends Thread{
              int a=0;
              String name;
              public T(String str) {
                     this.name=str;
              }
              
              @Override
              public void run() {
                     // TODO Auto-generated method stub
                     while(a<10) {
                           a++;
                           System.out.println(name+" :   "+a);
                     }
                     
              }      
       
}
public class Test{
       
       public static void main(String args[]) {
             
              T t1=new T("线程1");
              T t2=new T("线程2");
              t1.start();
              t2.start();
       }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!