Java多线程_Java多线程技能(2)

isAlive方法

主要是用来判断当前线程是否处于活动状态。

package multiply.com.test;

public class MyThread extends Thread {
    
    
    @Override
    public void run() {
    
    
        System.out.println("run="+this.isAlive());
    }
}
package multiply.com.test;

public class Run {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
    	MyThread myThread = new MyThread();
    	System.out.println("begin="+myThread.isAlive());
    	myThread.start();
    	Thread.sleep(1000);
    	System.out.println("end="+myThread.isAlive());
    }
}

begin=false
run=true
end=false
先是main线程启动,然后myThread线程启动,main线程休眠,main线程再启动。

sleep()方法

在这里插入图片描述

package multiply.com.test;

public class MyThread extends Thread{
    
    
    @Override
    public void run() {
    
    
        try {
    
    
        	System.out.println("run begin:"+this.currentThread().getName()); 
            Thread.sleep(2000);
            System.out.println("run end:"+this.currentThread().getName());
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }
}

package multiply.com.test;

public class Run {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
    	MyThread myThread = new MyThread();
    	System.out.println("begin");
    	//这里是main线程中调用myThread线程中的run方法,所以当前线程还是main线程
    	//myThread.run();
    	//main线程与myThread线程是异步执行的,先执行main线程,然后执行myThread线程
    	myThread.start();
    	System.out.println("end");
    }
}

begin
end
run begin:Thread-0
run end:Thread-0

采用myThread.run():
begin
run begin:main
run end:main
end

getId()方法

作用就是获得线程的唯一标识。
在这里插入图片描述

停止线程

停止不了的线程

interrupt()方法仅仅在当前线程中打了一个暂停的标记,并不是真的停止线程。

判断线程是否是停止状态

在这里插入图片描述

package multiply.com.test;

public class MyThread extends Thread {
    
    
    @Override
    public void run() {
    
    
        super.run();
        for (int i = 0; i < 200; i++) {
    
    
            System.out.println("i=" + (i + 1));
        }
    }
}
package multiply.com.test;

public class Run {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            MyThread thread = new MyThread();
            thread.start();
            //主线程休眠1ms
            Thread.sleep(1);
            //休眠结束,两个线程同时运行,thread打上false标记,中断了,但程序并没有停止。
            thread.interrupt();
            //判断当前线程(main线程)没有中断。
            System.out.println("是否停止1?" + thread.interrupted());
            System.out.println("是否停止2?" + thread.interrupted());
        } catch (InterruptedException e) {
    
    
            System.out.println("main catch");
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

在这里插入图片描述
当前线程main线程没有中断。

package multiply.com.test;

public class Run {
    
    
    public static void main(String[] args) {
    
    
    	//主线程打标记,中断,但是并没有真正中断,程序还是继续运行
        Thread.currentThread().interrupt();
        System.out.println("是否停止1?" + Thread.interrupted());
        System.out.println("是否停止2?" + Thread.interrupted());
    }
}

是否停止1?true
是否停止2?false
在这里插入图片描述

package multiply.com.test;

public class Run {
    
    
    public static void main(String[] args) {
    
    
    	try {
    
    
            MyThread thread = new MyThread();
            thread.start();
            Thread.sleep(1);
            thread.interrupt();
            //判断是thread对象是否中断,但并不清理标记
            System.out.println("是否停止1?" + thread.isInterrupted());
            System.out.println("是否停止2?" + thread.isInterrupted());
        } catch (InterruptedException e) {
    
    
            System.out.println("main catch");
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

在这里插入图片描述

能停止的线程–异常法

package multiply.com.test;

public class MyThread extends Thread {
    
    
    @Override
    public void run() {
    
    
        super.run();
        for (int i = 0; i < 200; i++) {
    
    
        	if(this.interrupted())
        	{
    
    
        		System.out.println("已经是停止状态!我要退出了!" );
        		break;
        	}
            System.out.println("i=" + (i + 1));
        }
        System.out.println("程序还在运行!");
    }
}
package multiply.com.test;

public class Run {
    
    
    public static void main(String[] args) {
    
    
    	try {
    
    
            MyThread thread = new MyThread();
            thread.start();
            Thread.sleep(1);
            thread.interrupt();
        } catch (InterruptedException e) {
    
    
            System.out.println("main catch");
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

在这里插入图片描述
如何解决程序还在继续运行呢?

package multiply.com.test;

public class MyThread extends Thread {
    
    
    @Override
    public void run() {
    
    
        super.run();
        try 
        {
    
    
        	for (int i = 0; i < 200; i++) {
    
    
        		if(this.interrupted())
        		{
    
    
        			System.out.println("已经是停止状态!我要退出了!" );
        			throw new InterruptedException();
        		}
        		System.out.println("i=" + (i + 1));
        	}
        	System.out.println("程序还在运行!");
        }catch(InterruptedException e) {
    
    
        	System.out.println("进入到catch了!");
        	e.printStackTrace();
        }
    }
}

在这里插入图片描述

在沉睡中停止

package multiply.com.test;

public class MyThread extends Thread {
    
    
    @Override
    public void run() {
    
    
        super.run();
        try 
        {
    
    
        	System.out.println("run begin");
        	Thread.sleep(200000);
        	System.out.println("run end");
        }catch(InterruptedException e) {
    
    
        	System.out.println("进入到catch了!"+this.isInterrupted());
        	e.printStackTrace();
        }
    }
}
package multiply.com.test;

public class Run {
    
    
    public static void main(String[] args) {
    
    
    	try {
    
    
            MyThread thread = new MyThread();
            thread.start();
            Thread.sleep(200);
            thread.interrupt();
        } catch (InterruptedException e) {
    
    
            System.out.println("main catch");
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

在这里插入图片描述
在这里插入图片描述
所以this.isInterrupted()在这里显示的就是false。

能停止的线程–暴力停止

在这里插入图片描述
在这里插入图片描述

package multiply.com.test;

public class SynchronizedObject {
    
    
    private String username = "a";
    private String password = "aa";

    public String getUsername() {
    
    
        return username;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }

    synchronized public void printString(String username, String password) {
    
    
        try {
    
    
            this.username = username;
            Thread.sleep(100000);
            this.password = password;
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }
}
package multiply.com.test;

public class MyThread extends Thread {
    
    
    private SynchronizedObject object;

    public MyThread(SynchronizedObject object) {
    
    
        super();
        this.object = object;
    }

    @Override
    public void run() {
    
    
        object.printString(" b", "bb");
    }
}
package multiply.com.test;

public class Run {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            SynchronizedObject object = new SynchronizedObject();
            MyThread thread = new MyThread(object);
            thread.start();
            Thread.sleep(500);
            thread.stop();
            System.out.println(object.getUsername() + " " + object.getPassword());
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }
}

b aa

使用return停止线程

在这里插入图片描述

package multiply.com.test;

public class MyThread extends Thread {
    
    
    @Override
    public void run() {
    
    
    	while(true)
    	{
    
    
    		if(this.interrupted())
    		{
    
    
    			System.out.println("停止了");
    			return;
    		}
    		System.out.println("运行中");
    	}
    }
}
package multiply.com.test;

public class Run {
    
    
	public static void main(String[] args) throws InterruptedException {
    
    
		MyThread thread = new MyThread();
		thread.start();
		Thread.sleep(500);
		thread.interrupt();
	}
}

在这里插入图片描述

暂停线程

独占

在这里插入图片描述

package multiply.com.test;

public class SynchronizedObject {
    
    
    synchronized  public void printString() {
    
    
        System.out.println("begin");
        if (Thread.currentThread().getName().equals("a")) {
    
    
            System.out.println("a线程永远suspend了!");
            Thread.currentThread().suspend();
        }
        System.out.println("end");
    }
}
package multiply.com.test;

public class Run {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            final SynchronizedObject object = new SynchronizedObject();
            Thread thread1 = new Thread() {
    
    
                @Override
                public void run() {
    
    
                    object.printString();
                }
            };
            thread1.setName("a");
            thread1.start();
            Thread.sleep(1000);
            Thread thread2 = new Thread() {
    
    
                @Override
                public void run() {
    
    
                    System.out.println("thread2启动了,但进不了printString()方法!只打印了一个begin");
                    System.out.println("因为printString()方法被a线程锁定,并且永远suspend暂停了");
                    object.printString();
                }
            };
            thread2.start();
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }
}

begin
a线程永远suspend了!
thread2启动了,但进不了printString()方法!只打印了一个begin
因为printString()方法被a线程锁定,并且永远suspend暂停了

package multiply.com.test;

public class MyThread extends Thread {
    
    
	private long i = 0;
    @Override
    public void run() {
    
    
    	while(true)
    	{
    
    
    		i++;
    		System.out.println(i);
    	}
    }
}
package multiply.com.test;

public class Run {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
        	MyThread thread1 = new MyThread();
            thread1.start();
            Thread.sleep(1000);
            thread1.suspend();
            System.out.println("main end");
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }
}

没有打印出main end在这里插入图片描述
在这里插入图片描述

不同步

package multiply.com.test;

public class MyObject {
    
    
    private String username = "1";
    private String password = "11";

    public void setValue(String u, String p) {
    
    
        this.username = u;
        if (Thread.currentThread().getName().equals("a")) {
    
    
            System.out.println("停止a线程");
            Thread.currentThread().suspend();
        }
        this.password = p;
    }

    public void printUsernamePassword() {
    
    
        System.out.println(username + " " + password);
    }
}
package multiply.com.test;

public class Run {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        final MyObject myObject = new MyObject();
        Thread thread1 = new Thread() {
    
    
            @Override
            public void run() {
    
    
                myObject.setValue("a", "aa");
            }
        };
        thread1.setName("a");
        thread1.start();
        Thread.sleep(500);
        Thread thread2 = new Thread() {
    
    
            @Override
            public void run() {
    
    
                myObject.printUsernamePassword();
            }
        };
        thread2.start();
    }
}

停止a线程
a 11

yeild方法

在这里插入图片描述
在这里插入图片描述

线程优先级

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
优先级具有规则性:

package multiply.com.test;

import java.util.Random;
public class MyThread1 extends Thread {
    
    
    @Override
    public void run() {
    
    
        long beginTime = System.currentTimeMillis();
        long addResult = 0;
        for (int j = 0; j < 10; j++) {
    
    
            for (int i = 0; i < 50000; i++) {
    
    
                Random random = new Random();
                random.nextInt();
                addResult = addResult + i;
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("*****thread 1 use time=" + (endTime - beginTime));
    }

}
package multiply.com.test;

import java.util.Random;
public class MyThread2 extends Thread {
    
    
    @Override
    public void run() {
    
    
        long beginTime = System.currentTimeMillis();
        long addResult = 0;
        for (int j = 0; j < 10; j++) {
    
    
            for (int i = 0; i < 50000; i++) {
    
    
                Random random = new Random();
                random.nextInt();
                addResult = addResult + i;
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("*****thread 2 use time=" + (endTime - beginTime));
    }
}
package multiply.com.test;

public class Run {
    
    
    public static void main(String[] args) {
    
    
        for (int i = 0; i < 5; i++) {
    
    
            MyThread1 thread1 = new MyThread1();
            thread1.setPriority(10);
            thread1.start();
            MyThread2 thread2 = new MyThread2();
            thread2.setPriority(1);
            thread2.start();
        }
    }
}

*****thread 1 use time=421
*****thread 1 use time=484
*****thread 2 use time=508
*****thread 1 use time=510
*****thread 1 use time=514
*****thread 2 use time=522
*****thread 2 use time=522
*****thread 2 use time=524
*****thread 2 use time=525
*****thread 1 use time=527
在这里插入图片描述
优先级具有随机性:
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42148307/article/details/120732618