1.yield()方法使用
yield()释放当先CPU执行权;
public class helloWord01 {
public static void main(String[] args) {
System.out.println("hellow Word01");
Thread thread0 = new HelloThread0();
Thread thread1 = new HelloThread1();
thread0.start();
thread1.start();
}
}
class HelloThread0 extends Thread{
@Override
public void run() {
for(int i = 0;i<100 ;i++){
if(i%2 == 0){
System.out.println(Thread.currentThread().getName() + "0 :" + i);
}
if(i % 20 == 0){
yield();
}
}
}
}
class HelloThread1 extends Thread{
@Override
public void run() {
for(int i = 0;i<100 ;i++){
if(i%2 == 0){
System.out.println(Thread.currentThread().getName() + "1 :" + i);
}
if(i % 20 == 0){
yield(); //释放当先CPU执行权
}
}
}
}
join()方法
在线程a中调用b线程的join方法,a线程会进入阻塞状态,等代b线程执行完后,才继续后续操作。
public class helloWord01 {
public static void main(String[] args) {
System.out.println("hellow Word01");
Thread thread0 = new HelloThread0();
thread0.start();
for(int i = 0;i<10 ;i++){
System.out.println(Thread.currentThread().getName() + "main :" + i);
if(i == 2){
try {
thread0.join(); //等到HelloThread0执行完成后,再继续执行主程序
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class HelloThread0 extends Thread{
@Override
public void run() {
for(int i = 0;i<10 ;i++){
System.out.println(Thread.currentThread().getName() + "0 :" + i);
}
}
}
打印信息:
hellow Word01
mainmain :0
mainmain :1
mainmain :2
Thread-00 :0
Thread-00 :1
Thread-00 :2
Thread-00 :3
Thread-00 :4
Thread-00 :5
Thread-00 :6
Thread-00 :7
Thread-00 :8
Thread-00 :9
mainmain :3
mainmain :4
mainmain :5
mainmain :6
mainmain :7
mainmain :8
mainmain :9
stop(),强行停止线程,不推荐
sleep(long)
让当前线程“睡眠”制定的毫秒,在指定的时间内,当前线程是阻塞状态。
isAlive()
判断当前线程是否存活。
setPrior(INT)
设置线程的优先级 thread0.setPriority(Thread.MAX_PRIORITY);
线程安全
1.同步代码块
synchronize(同步监视器){
// 需要被同步的代码
}
说明:
1.操作共享数据的代码,即为需要被同步的代码块;
2.共享数据:多个线程共同操作的变量。
3.同步监视器,俗称;锁,任何一个类的对象,都可以充当锁。
要求:多个线程必须要共用同一把锁。
class sellTicketsAction implements Runnable {
private int ticket = 1000;
@Override
public void run() {
while (true) {
synchronized(this){
if(ticket > 0) {
System.out.println(Thread.currentThread().getName() + "卖票号为:" + ticket);
ticket--;
}
}else {
break;
}
}
}
}
2.同步方法。
private synchronized void action(){
//执行代码
}
总结: 1.同步方法仍然涉及到同步监视器,只是不需要我们显示的声明。
2.非静态的同步方法,同步监视器:this;静态的同步方法,同步监视器是:当前本身类。
3.lock锁
private ReentrantLock lock = new ReentrantLock();
lock.lock();
//需要执行的代码
lock.unlock();