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.youkuaiyun.com/qq_32823673/article/details/78657281