Java线程操作的常见方法【线程名称获取、设置、线程启动判断等】
人气:0本文实例讲述了Java线程操作的常见方法。分享给大家供大家参考,具体如下:
一 线程名称的操作
1 代码
public class GetNameThreadDemo extends Thread { public void run() { for( int i = 0; i < 5; ++i ) { printMsg(); try { Thread.sleep(1000); // 睡眠1秒 } catch( InterruptedException e ) { e.printStackTrace(); } } } public void printMsg() { // 获得运行此代码的线程的引用 Thread t = Thread.currentThread(); String name = t.getName(); System.out.println( "name = " + name ); } public static void main( String[] args ) { GetNameThreadDemo t1 = new GetNameThreadDemo(); t1.start(); for( int i = 0; i < 5; ++i ) { t1.printMsg(); try { Thread.sleep(1000); // 睡眠1秒 } catch( InterruptedException e ) { e.printStackTrace(); } } } }
2 运行
name = main
name = Thread-0
name = main
name = Thread-0
name = main
name = Thread-0
name = main
name = Thread-0
name = main
name = Thread-0
二 设置与获取线程名称
1 代码
public class GetSetNameThreadDemo implements Runnable { public void run( ) { Thread temp = Thread.currentThread( );//获取执行这条语句的线程实例 System.out.println("执行这条语句的线程名字:" + temp.getName( )); } public static void main(String[] args) { Thread t = new Thread(new GetSetNameThreadDemo( )); t.setName("线程_范例演示"); t.start(); } }
2 运行
执行这条语句的线程名字:线程_范例演示
三 判断线程是否启动
1 代码
public class StartThreadDemo extends Thread { public void run() { for( int i = 0; i < 5; ++i ) { printMsg(); } } public void printMsg() { // 获得运行此代码的线程的引用 Thread t = Thread.currentThread(); String name = t.getName(); System.out.println( "name = " + name ); } public static void main( String[] args ) { StartThreadDemo t = new StartThreadDemo(); t.setName( "test Thread" ); System.out.println( "调用start()方法之前 , t.isAlive() = " + t.isAlive() ); t.start(); System.out.println( "刚调用start()方法时 , t.isAlive() = " + t.isAlive() ); for( int i = 0; i < 5; ++i ) { t.printMsg(); } // 下面语句的输出结果是不固定的,有时输出false,有时输出true System.out.println( "main()方法结束时 , t.isAlive() = " + t.isAlive() ); } }
2 运行
调用start()方法之前 , t.isAlive() = false
刚调用start()方法时 , t.isAlive() = true
name = main
name = main
name = main
name = test Thread
name = main
name = test Thread
name = main
name = test Thread
main()方法结束时 , t.isAlive() = true
name = test Thread
name = test Thread
Process finished with exit code 0
更多java相关内容感兴趣的读者可查看本站专题:《Java进程与线程操作技巧总结》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。
您可能感兴趣的文章:
加载全部内容