首页 > 其他分享 >静态方法如何调用非静态方法,创建线程的方式

静态方法如何调用非静态方法,创建线程的方式

时间:2023-01-02 10:22:31浏览次数:34  
标签:调用 静态方法 int void public 线程 Main class

在静态方法中,new 一个类对象,用类对象调用非静态方法

第一种方式创建线程 public class Main {     private class MyRun implements Runnable{         public void run(){             for(int i=0; i<10; i++){                 System.out.println("MyRun"+i);             }         }     }     public void test(){         new Thread(new MyRun()).start();     }     public static void main(String[] args) {         new Main().test();             } } 第二种方式创建线程--lamdba表达式

 

 

import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main {     private class MyRun implements Runnable{         public void run(){             for(int i=0; i<10; i++){                 System.out.println("MyRun"+i);             }         }     }     public void test(){         new Thread(new MyRun()).start();     }     public void test2(){         new Thread(             ()->{                 for(int j=0;j<10;j++){                     System.out.println("test2--"+j);                 }             }         ).start();     }     public static void main(String[] args) {         new Main().test();         new Main().test2();     } }

标签:调用,静态方法,int,void,public,线程,Main,class
From: https://www.cnblogs.com/northli/p/17019467.html

相关文章