简单的Java例子程序

180个针对Java初学者的简单实例

 

在网上查了一些JAVA线程的例子.要么都是抄来抄去,要么就是复杂,对于初学者,很难去理解线程

为了让初学者更快的理解线程.我自己写了简单易懂.希望大家能理解


先看代码吧:

建一个主函数类:


    public static void main(String[] args) {
        
        thread1 thread1 = new thread1();//用Thread类的子类创建线程
        Thread thread2 = new Thread(new thread2());//用Runnable接口类的对象创建线程
        thread1.start();//strat()方法启动线程
        thread2.start();
        
    }



建第一个线程类:

public class thread1 extends Thread {

    @Override
    public void run() {

        try {
            Thread.sleep(7000);//主线程挂起7秒,之所以加这个方法是为了更好的理解线程.后面我会说的
            System.out.println("one is start....");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

建第二个线程类:

public class thread2 implements Runnable {

    public void run() {

        System.out.println("two is start ...");
    }

}


这些是原代码,当你运行,结果是two is start ... 然后过7秒one is start.... 不知道大家发现没有
主函数应该第一运行thread1.start() 这个类,输出结果是one is start.... 但是却没有.而是two is start ...
          thread1.start();//strat()方法启动线程
        thread2.start();

可以看出,启动线程的run()方法是通过调用线程的start()方法来实现的(见上例中主类),调用start()方法启动线程的run()方法不同于一般的调用方法,调用一般方法时,必须等到一般方法执行完毕才能够返回start()方法,而启动线程的run()方法后,start()告诉系统该线程准备就绪可以启动run()方法后,就返回start()方法执行调用start()方法语句下面的语句,这时run()方法可能还在运行,这样,线程的启动和运行并行进行,实现了多任务操作。
所以大家明白了吧,用了线程了,他们之间是互不影响的.thread1.start() 还没有结束,对thread2.start()没有影响 现在也明白我在thread1类中加Thread.sleep(7000)的意义了吧
就是为了更好的理解线程!

 

厦门事业单位招聘网:http://www.xmsydw.com

 

posted @ 2012-08-08 10:09  java简单例子  阅读(1250)  评论(0)    收藏  举报