从C++基础开始学JAVA笔记-DAY1

1. HelloWorld.java

编译方法:

$ javac helloWorld.java

源码:

public class HelloWorld{
    public static void main(String[] args){
        System.out.println("Hello World!");
    }   
}

注意这个文件名一定要和类名相同,否则会报错:

$ javac helloWorld.java 
helloWorld.java:7: error: class HelloWorld is public, should be declared in a file named HelloWorld.java
public class HelloWorld{
       ^
1 error

2. example.java多线程引入

public class example{
    public static void main(String[] args){
        MyThread myThread = new MyThread();
        System.out.println("Init MyThread ...");
        myThread.run();
        while(true){
            System.out.println("In main method ...");
        }
    }   
}

class MyThread{
    public void run(){
        while(true){
            System.out.println("Mythread run method ...");
        }
    }   
}

会生成两个文件:

example.class MyThread.class

执行:

java example

Output:

Mythread run method ...
......
Mythread run method ...
无限循环,不会跑到main method.

3.目标:让上面的例子中两个线程都跑起来
多线程方法1Thread

public class MultiThread{
    public static void main(String[] args){
        MyThread myThread = new MyThread();
        myThread.start();
        System.out.println("Init MyThread ...");
        //myThread.run();
        while(true){
            System.out.println("In main method ...");
        }
    }
}

class MyThread extends Thread{
    public void run(){
        while(true){
            System.out.println("Mythread run method ...");
        }
    }
}

注意这里是冲洗了Thread的run方法,不要再去调用一遍run()方法,否则还是不会执行到main里面打印的”In main method …”
多线程方法2 Runnable
方法1中通过继承Thread类实现多线程,但是这种方式有一定的局限性。因为在java中只支持单继承,一个类一旦继承了某个父类就无法再继承Thread类,比如学生类Student继承了person类,就无法再继承Thread类创建的线程。为了克服这种弊端,Thread类提供了另外一种构造方法Thread(Runnable target),其中Runnable是一个接口,它只有一个run()方法。当通过Thread(Runnable target)构造方法创建一个线程对象时,只需该方法传递一个实现了Runnable接口的实例对象,这样创建的线程将调用实现了Runnable接口中的run()方法作为运行代码,同样的,不需要调用Thread类中的run()方法。

public class MultiThreadRunnable{
    public static void main(String[] args){
        MyThread myThread = new MyThread();
        Thread thread = new Thread(myThread);
        thread.start();
        System.out.println("Init MyThread ...");
        while(true){
            System.out.println("In main method ...");
        }
    }
}

class MyThread implements Runnable{
    public void run(){
        while(true){
            System.out.println("Mythread run method ...");
        }
    }
}

参考文献:
http://blog.csdn.net/qq_32823673/article/details/78657281

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值