线程可以驱动任务,因此,我们需要一种描述任务的方式,我们定义多线程任务有两种方式可以实现,一种是继承Thread类,重写run方法,如下所示,我们使用这种方法定义了一个多线程的计数器。
</pre><pre name="code" class="java">package thread;
public class ThreadCreate extends Thread{
private static int count=0;
private int task;
public ThreadCreate(int task){
this.task = task;
}
@Override
public void run() {
while(count<100){
count++;
System.out.println(status());
}
}
public String status(){
return ""+task+":"+count;
}
public static void main(String[] args) {
ThreadCreate thread = new ThreadCreate(1);
thread.run();
}
}
</pre><pre name="code" class="java">如代码所示,我们定义了一个计数器的任务,在run方法中进行计数,并且输出当前的执行状态。在主方法中创建了一个线程去执行任务。运行结果如下:</pre>1:11:21:31:41:51:61:71:81:91:101:111:121:131:141:151:161:171:181:191:201:211:221:231:241:251:261:271:281:291:301:311:321:331:341:351:361:371:381:391:401:411:421:431:441:451:461:471:481:491:501:511:521:531:541:551:561:571:581:591:601:611:621:631:641:651:661:671:681:691:701:711:721:731:741:751:761:771:781:791:801:811:821:831:841:851:861:871:881:891:901:911:921:931:941:951:961:971:981:991:100<p></p><p><span style="white-space:pre"></span></p><p><span style="white-space:pre">我们可以知道,当前只有一个线程在执行计数操作,加上主线程,在我们现在的应用中一共有两个线程在执行。下面我们一起执行多个线程,观察执行结果会有什么变化。为使用多个线程进行计数,我们对主方法进行如下的变动。</span></p><p><span style="white-space:pre"></span></p><pre name="code" class="java">public static void main(String[] args) {
for(int i=0;i<10;i++){
ThreadCreate thread = new ThreadCreate(i);
thread.run();
}
}运行,观察结果.我们会发现,多个线程一起交替的执行计数任务。
除了继承Thread类来定义我们的任务之外呢,我们还有另外一种方式可以定义我们的任务,那就是实现Runnable接口。如下所示,我们对上面的计数器换一种方式进行定义。
public class Thread2 implements Runnable {
private static int count;
@Override
public void run() {
while(count<100){
count++;
System.out.println(count);
}
}
public static void main(String[] args) {
new Thread(new Thread2()).start();
}
}
241

被折叠的 条评论
为什么被折叠?



