9. Java多线程编程题:
启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20....以此类推, 直到打印到75. 程序的输出结果应该为:
线程1: 1
线程1: 2
线程1: 3
线程1: 4
线程1: 5
线程2: 6
线程2: 7
线程2: 8
线程2: 9
线程2: 10
...
线程3: 71
线程3: 72
线程3: 73
线程3: 74
线程3: 75
具体的java多线程知识请看我转载的另一篇文章。
建立了自己的threaddemo函数。同时调用run函数来进行执行。
每次一个thread执行,利用join()等待这个thread终止以后下一个thread继续执行
package test;
public class ThreadMain{
public static void main(String argv[]){
ThreadMain test = new ThreadMain();
test.Method2();
// test.Method2();
}
// 第二种方法:join()
public static int i = 1;
public void Method2(){
ThreadDemo th1 = new ThreadDemo("thread1");
ThreadDemo th2 = new ThreadDemo("thread2");
ThreadDemo th3 = new ThreadDemo("thread3");
// 执行第一个线程
for(int k = 0;k<5;k++)
{
int j = th1.run(i);
try{
th1.join();
}catch(InterruptedException e){
}
int l = th2.run(j);
try{
th2.join();
}catch(InterruptedException e)
{}
i = th3.run(l);
try{
th3.join();
}
catch(InterruptedException e)
{}
}
}
}
package test;
class ThreadDemo extends Thread{
String threadname;
ThreadDemo(String szName)
{
super(szName);
threadname = szName;
}
ThreadDemo()
{
}
// 重载run函数
public int run(int i)
{
for(int j = i;j<i+5;j++)
{
System.out.println("now "+threadname+" "+j);
}
i+=5;
return i;
}
}