- 首页 > it技术 > >
java|使用线程Thread和Runnable输出1到100之间的偶数
javathreadjava多线程Runnable
package cn.thread.demo;
//输出1到100之间的偶数
public class ThreadTest extends Thread{ public void run() {
for (int i = 1;
i <=100;
i++) {
if(i%2==0){
System.out.println("线程名字:"+Thread.currentThread().getName()+":"+i);
}
}
}
public static void main(String[] args) {
ThreadTest tt=new ThreadTest();
//tt.setName(name);
//tt.start();
//可以设置线程getName
Thread tr=new Thread(tt,"线程A");
tr.start();
}
}
package cn.thread.demo;
//输出1到100之间的偶数
public class RunnableTest implements Runnable {
private int count=0;
public void run() {
while(count<100){
count++;
if(count%2==0){
System.out.println("线程名字:"+Thread.currentThread().getName()+":"+count);
}
}
}
public static void main(String[] args) {
RunnableTest ra=new RunnableTest();
//这种方式要调用setName()或其它Thread方法,需引用Thread对象
Thread tr=new Thread(ra,"B线程");
//tr.setName("B线程");
tr.start();
}
}
推荐阅读