JAVA线程

最近复习了一下线程,分享一下创建线程的几种方式。
第一种创建一个线程类,重写run方法。

```
public class Mythread extends Thread{
    private int number;
    @Override
    public void run() {
        while(number<100){
            System.out.println(Thread.currentThread().getName()+" "+number++);
        }
        try{
            Thread.sleep(500);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
```

测试类实现:

```
public class ThreadDemo {
    public static void main(String[] args) {
        Mythread my=new Mythread();
        Thread thread=new Thread(my);
        thread.setName("线程1->");
        thread.start();
    }
}

```

第二种方式呢就是实现Runnable接口实现run方法

```
public class MyThread2 implements  Runnable{
    @Override
    public void run() {
        int i=1;
        while(i<=100){
            System.out.println(Thread.currentThread().getName()+"\t"+i++);
        }
        try {
            Thread.sleep(500);
        }catch (Exception e){
            e.printStackTrace();

        }
    }

}


```

测试类:

```
public class ThreadDemo {
    public static void main(String[] args) {
        MyThread2 my2=new MyThread2();
        Thread thread=new Thread(my2);
        thread.setName("线程1->");
        thread.start();
    }
}

```

第三种呢,就是匿名内部类了,比较简单,就不说了。

```
public class ThreadDemo2 {
    public static void main(String[] args) {
     new Thread(new Runnable() {
         @Override
         public void run() {
             int i=1;
             while(i<=100){
                 System.out.println(Thread.currentThread().getName()+"\t"+i++);
             }
             try {
                 Thread.sleep(500);
             }catch (Exception e){
                 e.printStackTrace();

             }
         }
     }).start();

    }
}
```
posted @ 2022-04-27 21:18  长情c  阅读(30)  评论(0)    收藏  举报