Thread mainメソッドのThread
2763 ワード
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);
}
}
印刷結果は不確定ですが、なぜですか?2つのスレッドがあります.1つはtで、1つの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オブジェクトによって制御されます.この方法は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);
}
}
}