1. 获取线程的名字:
String name = currentThread.getName();
2. 设置线程的名字:
currentThread.setName(“t1”);
3. 获取当前线程:
Thread currentThread = Thread.currentThread();
4. 唤醒线程
package Demo;
public class ThreadMethod {
public static void main ( String[ ] args) {
ThreadM t = new ThreadM ( ) ;
Thread t1 = new Thread ( t) ;
t1. setName ( "t1" ) ;
t1. start ( ) ;
Thread currentThread = Thread. currentThread ( ) ;
currentThread. setName ( "main" ) ;
String name = currentThread. getName ( ) ;
for ( int i = 0 ; i < 100 ; i++ ) {
System. out. println ( name + "--->" + i) ;
}
}
}
class ThreadM implements Runnable {
@Override
public void run ( ) {
Thread currentThread = Thread. currentThread ( ) ;
String name = currentThread. getName ( ) ;
for ( int i = 0 ; i < 100 ; i++ ) {
System. out. println ( name + "--->" + i) ;
}
}
}
唤醒线程
package Demo;
public class WakeUp {
public static void main ( String[ ] args) {
Thread t = new Thread ( new Wake ( ) ) ;
t. setName ( "t" ) ;
t. start ( ) ;
try {
Thread. sleep ( 5000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
t. interrupt ( ) ;
}
}
class Wake implements Runnable {
@Override
public void run ( ) {
System. out. println ( Thread. currentThread ( ) . getName ( ) + " -> begain" ) ;
try {
Thread. sleep ( 1000 * 60 * 24 * 365 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System. out. println ( Thread. currentThread ( ) . getName ( ) + " -> end" ) ;
}
}
5. 终止线程
package Demo;
public class StopThread {
public static void main ( String[ ] args) throws InterruptedException {
StopTest s = new StopTest ( ) ;
Thread t = new Thread ( s) ;
t. setName ( "t" ) ;
t. start ( ) ;
Thread. sleep ( 5000 ) ;
s. run = false ;
}
}
class StopTest implements Runnable {
boolean run = true ;
public void run ( ) {
for ( int i = 0 ; i < 100 ; i++ ) {
if ( run) {
try {
Thread. sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System. out. println ( Thread. currentThread ( ) . getName ( ) + "--->" + i) ;
} else {
return ;
}
}
}
}