1.取得线程名称
getName();
2.取得当前线程对象
currentThread();
3.判断线程是否启动
isAlive();
4.线程的强行运行
join();
示例:
class RunnableDemo implements Runnable {
private String name;
public RunnableDemo(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 100; i++) {
// 打印出当前线程对象的名称
// System.out.println("当前线程对象:" + Thread.currentThread().getName());
System.out.println(name + ":" + i);
}
}
}
public class ThreadDemo03 {
public static void main(String[] args) {
RunnableDemo r = new RunnableDemo("A");
Thread t = new Thread(r);
// 判断线程是否启动
// System.out.println(t.isAlive());//启动前为false
t.start();
// System.out.println(t.isAlive());//启动后为true
for (int i = 0; i < 50; i++) {// 主线程运行到i>10时,刺激线程t强行执行
if (i > 10) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("主线程" + i);
}
}
}
5.线程的休眠
sleep()
.
.
示例:
class RunnableDemo implements Runnable {
private String name;
public RunnableDemo(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(1000);
System.out.println(name + ":" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadDemo03 {
public static void main(String[] args) {
RunnableDemo r = new RunnableDemo("A");
Thread t = new Thread(r);
t.start();
}
}
结果:
每秒钟显示一行数据
6.线程的礼让
示例:
class RunnableDemo implements Runnable {
private String name;
public RunnableDemo(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println(name + ":" + i);
if (i==10) {
System.out.println("礼让");
Thread.yield();// 礼让方法
}
}
}
}
public class ThreadDemo03 {
public static void main(String[] args) {
RunnableDemo r1 = new RunnableDemo("A");
RunnableDemo r2 = new RunnableDemo("B");
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
结果: