2017年10月25日 22:47:09
一、可以用匿名类和lambda两个种方式创建多线程。
1.利用匿名内部类创建多线程并开启。
- new Thread() {//创建方式1
- public void run() {
- for(int x=0; x<50; x++) {
- System.out.println(Thread.currentThread().getName()+"....x="+x);
- }
- }
- }.start();
- Runnable r = new Runnable() {//创建方式2
- public void run() {
- for(int x=0; x<50; x++) {
- System.out.println(Thread.currentThread().getName()+"....z="+x);
- }
- }
- };
- new Thread(r).start();
2.利用lambda方式创建多线程并开启。
- Runnable r = ()->{
- for(int x=0; x<50; x++){
- System.out.println(Thread.currentThread().getName()+"....z="+x);
- }
- };
- new Thread(r).start();
1.第一题
- class Test implements Runnable
- {
- public void run(Thread t)
- {}
- }
- //如果错误 错误发生在哪一行?
- //答案:错误在第一行,应该被abstract修饰,因为run()抽象方法没有被重写。
2.第二题
- class ThreadTest
- {
- public static void main(String[] args)
- {
- new Thread(new Runnable()
- {
- public void run()
- {
- System.out.println("runnable run");
- }
- })
- {
- public void run()
- {
- System.out.println("subThread run");
- }
- }.start();
- }
- }
答案:将会输出subThread run,必须以子类为主,若子类没有,在输出参数任务中的runnable run,若都没有,则执行Thread类中默认的run()方法。