如何在JAVA代码中实现线程 [英] HOW TO IMPLEMENT THREADS IN JAVA CODE

查看:102
本文介绍了如何在JAVA代码中实现线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JAVA代码中实现线程

HOW TO IMPLEMENT THREADS IN JAVA CODE

推荐答案

java中的线程可以通过两种方式实现。

1.继承线程类。

2.通过实现Runnable接口。



Inherting Thread Class



Threads in java can be implemented in two ways.
1. By inheriting the Thread class.
2. By implementing Runnable Interface.

Inherting Thread Class


// ThreadDemo.java
class ThreadDemo
{
   public static void main (String [] args)
   {
      MyThread mt = new MyThread ();
      mt.start ();
      for (int i = 0; i < 50; i++)
           System.out.println ("i = " + i + ", i * i = " + i * i);
   }
}
class MyThread extends Thread
{
   public void run ()
   {
      for (int count = 1, row = 1; row < 20; row++, count++)
      {
           for (int i = 0; i < count; i++)
                System.out.print ('*');
           System.out.print ('\n');
      }
   }
}





实施Runnable接口



Implementing Runnable Interface

package com.myjava.threads;
 
class MyRunnableThread implements Runnable{
 
    public static int myCount = 0;
    public MyRunnableThread(){
         
    }
    public void run() {
        while(MyRunnableThread.myCount <= 10){
            try{
                System.out.println("Expl Thread: "+(++MyRunnableThread.myCount));
                Thread.sleep(100);
            } catch (InterruptedException iex) {
                System.out.println("Exception in thread: "+iex.getMessage());
            }
        }
    } 
}
<span class="ild18a07" id="ild18a07_5">public class</span> RunMyThread {
    public static void main(String a[]){
        System.out.println("Starting Main Thread...");
        MyRunnableThread mrt = new MyRunnableThread();
        Thread t = new Thread(mrt);
        t.start();
        while(MyRunnableThread.myCount <= 10){
            try{
                System.out.println("Main Thread: "+(++MyRunnableThread.myCount));
                Thread.sleep(100);
            } catch (InterruptedException iex){
                System.out.println("Exception in main thread: "+iex.getMessage());
            }
        }
        System.out.println("End of Main Thread...");
    }
}





祝你好运


通过了解 [ ^ ]它们。


一般说来,你有两个选择来实现一个线程:

1)写一个java.lang.Thread的子类;



Generally speaking, you have two choices to implement a thread:
1) Write a subclass of java.lang.Thread;

class YouClass extends Thread
{
   public void run(){
      //Your execution code goes here  
   }

}





2)实现java.lang.Runnable接口。





2) Implement java.lang.Runnable interface.

class YourClass implements Runnable
{
    public void run(){
      //Your execution code goes here  
   }
}


这篇关于如何在JAVA代码中实现线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆