标签:blog http io java ar 2014 art 问题 on
1、类结构,首先有两个类,一个是测试类Main,一个是线程类MyThread。
2、MyThread
package com.test.thread; import java.lang.management.ThreadInfo; public class MyThread implements Runnable { String name=null; MyThread(String name) { this.name=name; } @Override public void run() { // TODO Auto-generated method stub while(true) { System.out.println(name+":输出结果..."); } } }
package com.test.thread; public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub MyThread mya=new MyThread("线程A"); Thread testA=new Thread(mya); testA.start(); MyThread myb=new MyThread("线程B"); Thread testB=new Thread(myb); testB.start(); } }
3、输出结果
4、进阶版
用上面的截图还不好说明问题,因为运行速度比较快,看不出两者交替运行,如果在线程中假如线程休眠函数,让线程运行一段时间就休眠,然后重新恢复会比较直观,改动代码如下。
package com.test.thread; import java.lang.management.ThreadInfo; public class MyThread implements Runnable { String name=null; MyThread(String name) { this.name=name; } @Override public void run() { // TODO Auto-generated method stub while(true) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(name+":输出结果..."); } } }
标签:blog http io java ar 2014 art 问题 on
原文地址:http://blog.csdn.net/itbuluoge/article/details/39455797