一 取得和设置线程名称
在Thread的类中,可以通过getName()方法取得线程名称,通过setName()设置下那成名称。
线程的名称一般在线程启动之前设置,也允许为已经运行的线程设置,允许两个Thread类有相同的名字。
如果程序没有个线程指定名称,则系统会自动给线程分配一个。
代码如下
class MyThread implements Runnable //实现Runnable接口
{
public void run() //覆写run()方
{
for(int i=0;i<=5;i++)
{
System.out.println(Thread.currentThread().getName()//取得当前线程名称
+"运行,i="+i) ;
}
}
}
public class ThreadNameDemo01
{
public static void main(String[] args)
{
MyThread mt = new MyThread() ; //实例化Runnable子类对象
new Thread(mt).start() ; //系统自动设置线程名称
new Thread(mt,"线程A").start() ;//手动设置线程名称
new Thread(mt).start() ; //系统自动设置线程名称
new Thread(mt,"新城B").start() ;//手动设置线程名称
}
}
1.1 取得当前线程
程序通过 currentThread()方法取得当前正在运行的线程对象。
1.2 线程的强制运行
在线程操作中,可以使用join()方法让一个程序强制运行,线程强制运行期间,其他线程无法运行,必须等待此线程完成之后才能继续运行。
class MyThread implements Runnable
{
public void run() //覆写方法
{
for(int i=0;i<50;i++)
{
System.out.println(Thread.currentThread().getName()
+"运行,i"+i) ; //取得当前线程名称
}
}
}
public class ThreadJoinDemo01
{
public static void main(String[] args)
{
MyThread mt = new MyThread() ; //实例化 Runnable子类对象
Thread t = new Thread(mt,"线程A") ; //实例化Thread类对象
t.start() ; //启动线程
for(int i=0;i<50;i++)
{
if(i>10)
{
try
{
t.join() ; //线程强制运行
}
catch (InterruptedException e)
{
e.printStackTrace() ;
}
}
System.out.println("main线程运行"+i) ;
}
}
}
1.3 线程的休眠
在程序中允许一个线程暂时休眠,方法为Thread.sleep()
class MyThread implements Runnable
{
public void run() //覆写方法
{
for(int i=0;i<50;i++)
{
try
{
Thread.sleep(1000) ; //线程休眠
}
catch (InterruptedException e)
{
e.printStackTrace() ;
}
System.out.println(Thread.currentThread().getName()
+"运行,i"+i) ; //取得当前线程名称
}
}
}
public class ThreadSleepDemo01
{
public static void main(String[] args)
{
MyThread mt = new MyThread() ; //实例化 Runnable子类对象
Thread t = new Thread(mt,"线程A") ; //实例化Thread类对象
t.start() ; //启动线程
}
}
1.4 线程的中断
一个线程可以被另外一个线程中断其操作的状态,使用interrupt()方法完成。
class MyThread implements Runnable
{
public void run() //覆写run()方法
{
System.out.println("1,进入run()方法") ;
try
{
Thread.sleep(5000) ;
System.out.println("2,完成休眠") ;
}
catch (InterruptedException e)
{
System.out.println("3,休眠被终止") ;
}
System.out.println("4,run()方法结束") ;
}
}
public class ThreadInterruptDemo01
{
public static void main(String[] args)
{
MyThread mt = new MyThread() ; //实例化Runnable子类对象
Thread t = new Thread(mt,"线程A") ; //实例化Thread类对象
t.start() ; //启动线程
t.interrupt() ; //对象.方法() 中断线程执行
}
}