java多线程

Posted ruowei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java多线程相关的知识,希望对你有一定的参考价值。

  • 两种实现方式:一、实现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();
       }
}

以上是关于java多线程的主要内容,如果未能解决你的问题,请参考以下文章

什么是JAVA的多线程?

Java多线程 1.认识Java线程

Java多线程 5.栅栏

java 如何实现多线程

java中啥叫做线程?啥叫多线程?多线程的特点是啥

Java多线程-Java多线程概述