Role of Java currentthread() method
•
Java
Example 1
public class Run1
{
public static void main(String[] args)
{
//调用currentThread()方法输出当前线程名称
System.out.println(Thread.currentThread().getName());
}
}
package ch14;
public class MyThread06 extends Thread
{
public MyThread06()
{
//调用currentThread()方法输出当前线程名称
System.out.println("构造方法的打印:"+Thread.currentThread().getName());
}
@Override
public void run()
{
//调用currentThread()方法输出当前线程名称
System.out.println("run方法的打印:"+Thread.currentThread().getName());
}
}
package ch14;
public class Test09
{
public static void main(String[] args)
{
MyThread06 mythread=new MyThread06();
mythread.start();
//mythread.run();
}
}
构造方法的打印:main run方法的打印:Thread-0
构造方法的打印:main run方法的打印:main
Example 2
package ch14;
public class MyThread07 extends Thread
{
public MyThread07()
{
System.out.println("构造方法---开始");
System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName());
System.out.println("this.getName()="+this.getName());
System.out.println("构造方法---结束");
}
@Override
public void run()
{
System.out.println("run()方法---开始");
System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName());
System.out.println("this.getName()="+this.getName());
System.out.println("run()方法---结束");
}
package ch14;
public class Test10
{
public static void main(String[] args)
{
//创建MyThread07线程实例
MyThread07 myThread=new MyThread07();
//创建一个线程
Thread t1=new Thread(myThread);
//设置线程的名称
t1.setName("A");
//启动线程
t1.start();
}
构造方法---开始 Thread.currentThread().getName()=main this.getName()=Thread-0 构造方法---结束 run()方法---开始 Thread.currentThread().getName()=A this.getName()=Thread-0 run()方法---结束
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
