`
luzl
  • 浏览: 565465 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

Thread main方法中的Thread

    博客分类:
  • Java
阅读更多
package scjp;

public class Demo67 implements Runnable  
{  
    String myString = "Yes ";
    
    public void run()  
    {  
        this.myString = "No ";  
    }
    
    public static void main(String[] args)  
    {  
        Demo67 t = new Demo67();  
        Thread thread=new Thread(t); 
        System.out.println(thread.getId());
        System.out.println(Thread.currentThread().getId());
        for (int i=0; i < 10; i++)  
            System.out.print(t.myString);  
    }  
} 



打印结果是不确定的,为什么呢?是因为有两个线程一个是t,一个main里启动的主线程:

The 'main()' method in Java is referred to the thread that is running, whenever a Java program runs. It calls the main thread because it is the first thread that starts running when a program begins. Other threads can be spawned from this main thread. The main thread must be the last thread in the program to end. When the main thread stops, the program stops running.

Main thread is created automatically, but it can be controlled by the program by using a Thread object. The Thread object will hold the reference of the main thread with the help of currentThread() method of the Thread class.

--翻译
main()方法代表了正在运行的线程,因为任何Java程序的执行都首先生成main线程,其它线程都由其衍生,并且它是最后一个在程序中执行的线程,一旦main线程停止程序也就停止执行。
main线程是自动产生的,它可以被一个获得了main线程“引用”的 Thread 对象控制。这个方法是Thread.currentThread.
class MainThread 
{
    public static void main(String args [] ) 
    {
        Thread t = Thread.currentThread ( );

        System.out.println ("Current Thread : " + t);
        System.out.println ("Name : " + t.getName ( ) );
        System.out.println (" ");
        
        t.setName ("New Thread");
        System.out.println ("After changing name");
        System.out.println ("Current Thread : " + t);
        System.out.println ("Name : " + t.getName ( ) );
        System.out.println (" ");

        System.out.println ("This thread prints first 10 numbers");
        
        try 
        {
            for (int i=1; i<=10;i++) 
            {
                System.out.print(i);
                System.out.print(" ");
                Thread.sleep(1000);
            }
        } 
        catch (InterruptedException e) 
        {
            System.out.println(e); 
        }
   }
}




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics