很久没有用线程了,看面试题的时候正好有个线程的例子,简单的写了一个demo
线程要求如下:
创建两个线程,每个线程打印出线程名字后再睡眠,给其它线程以执行的机会,主线程也要打印出线程名字后再睡眠,每个线程前后共睡眠5 次。
代码如下:
package ThreadDemo; public class MultiThreadApp extends Thread { public static void main(String[] args){ Thread1 t1 = new Thread1(); Thread2 t2 = new Thread2(); try { t1.start(); t2.start(); for(int i=1;i<5;i++){ System.out.println("I am MaiThread"); Thread.sleep(3000); } } catch (InterruptedException e) { e.printStackTrace(); } } } class Thread1 extends Thread{ public void run(){ try { for(int i=0;i<=5;i++){ System.out.println("Thred A times=" + i); Thread.sleep(1000); } System.out.println("Thread A is over."); } catch (InterruptedException e) { e.printStackTrace(); } } } class Thread2 extends Thread{ public void run(){ try { for(int i=0;i<=5;i++){ System.out.println("Thred B times=" + i); Thread.sleep(1000); } System.out.println("Thread B is over."); } catch (InterruptedException e) { e.printStackTrace(); } } }
一个简单的线程例子,熟悉一下。网上看到的一篇博客不错地址是:http://lavasoft.blog.51cto.com/62575/27069/,有兴趣可以多了解一下。