📄 numberrunnable.java
字号:
//【例7.2】 声明自定义线程类实现Runnable接口实现奇数/偶数序列线程并发执行。
public class NumberRunnable implements Runnable
{
private int k;
public NumberRunnable(int k)
{
this.k = k;
}
public NumberRunnable()
{
this(0);
}
public void run()
{
int i = k;
System.out.println();
while (i<50)
{
System.out.print(i+" ");
i+=2;
}
System.out.println("结束!");
}
public static void main(String args[])
{
NumberRunnable odd = new NumberRunnable(1); //创建具有线程体的目标对象
Thread thread_odd = new Thread(odd,"奇数线程"); //以目标对象创建线程对象
thread_odd.start();
new Thread(new NumberRunnable(2),"偶数线程").start();
System.out.println("currentThread="+Thread.currentThread().getName());//获得当前线程对象名
System.out.println("activeCount="+thread_odd.activeCount());
}
}
/*
程序运行结果如下:
currentThread=main
activeCount=3
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34
36 38 40 42 44 46 48 结束!
31 33 35 37 39 41 43 45 47 49 结束!
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -