一个进程正在运行时至少会有1 个线程正在运行。
public class Test {
public static void main (String[] args) {
System.out .println(Thread.currentThread().getName());
}
}
输出结果:
main
分析:
一个名称叫做main的线程在执行main()方法中的代码。
线程是一个子任务,cpu是以随机的时间来调用线程中的run 方法。代码的运行结果与代码执行顺序或调用的顺序无关。
public class MyThread extends Thread {
private int count=5 ;
@Override
synchronized public void run () {
super .run();
count--;
System.out.println("由" +this .currentThread().getName()+" 计算,count=" +count);
}
}
分析:通过在run方法前加入synchronized 关键字,使多个线程在执行run方法时以排队的方法进行处理。当一个现在在调用run前,先判断run方法有没有被上锁,如果上锁,说明有其他线程正在调用run方法,必须等其他线程对run方法调用结束后才可以执行run方法。synchronized 可以在任意对象及方法上加锁,而加锁的这段代码称为“互斥区”或“临界区”。
currentThread()方法可返回该代码段是正在被哪个线程调用。
package mythread;
public class MyThread extends Thread {
public MyThread () {
System.out.println("构造方法的打印:" + Thread.currentThread().getName());
}
@Override
public void run () {
System.out.println("run方法的打印:" + Thread.currentThread().getName());
}
}
package run;
import mythread.MyThread;
public class Run2 {
public static void main (String[] args) {
MyThread mythread = new MyThread();
mythread.start();
}
}
输出结果:
构造方法的打印:main
run方法的打印:Thread-0
----------
package run;
import mythread.MyThread;
public class Run2 {
public static void main (String[] args) {
MyThread mythread = new MyThread();
mythread.run();
}
}
输出结果:
构造方法的打印:main
run方法的打印:main
isAlive() 的功能判断当前的进程是否处于活动状态
sleep() 的作用是在指定的毫秒数让当前“正在执行的线程”休眠,即暂停执行。这个“正在执行的线程”是指this.currentThread ()返回的线程
getId() 方法的作用是取得线程的唯一标识
interrupt()方法停止线程
this .interrupted()
this .isInterrupted()
使用return 停止线程
package extthread;
public class MyThread extends Thread {
@Override
public void run () {
while (true ) {
if (this .isInterrupted()) {
System.out.println("停止了!" );
return ;
}
System.out.println("timer=" + System.currentTimeMillis());
}
}
}
package test.run;
import extthread.MyThread;
public class Run {
public static void main (String[] args) throws InterruptedException {
MyThread t=new MyThread();
t.start();
Thread.sleep(4000 );
t.interrupt();
}
}
yield () 方法的作用是放弃当前的CPU资源,将它让给其他的任务占用CPU,但放弃的时间不确定。