Java多线程基础学习(一)
1. 创建线程
1.1 通过构造函数:public Thread(Runnable target, String name){} 或:public Thread(Runnable target){}
示例:
Thread thread1 = new Thread(new MyThread(), "mythread");<br/> class MyThread extends Thread(){<br/> public void run(){<br/> System.out.println("My First Thread');<br/> }<br/> }
1.2 直接实现Runnable接口:
示例:
Thread thread2 = new Thread(new Runnable{}{<br/> public void run(){<br/> System.out.println("This is my thread.");<br/> }<br/> });
2. 运行线程
thead1.start()
3. sleep
try{<br/> #休眠1000ms<br/> Thread.sleep(1000);<br/> }catch(InterruptedException e){<br/> e.printStackTrace();<br/> }
4. getName() 获取线程名字, getId()获取线程id
System.out.println(Thread.currentThread().getName() + “:”+ Thread.currentThread().getId);
5. 停止线程,
千万不用stop(),stop会立即终止线程。
通过interrupt()中断线程,但是中断并没有停止线程,配合异常来实现:
public class Main {<br/> public static void main(String[] args) throws InterruptedException {<br/> try{<br/> Thread thread1=new Thread(new TheThread(),"thread1");<br/> thread1.start();<br/> Thread.sleep(2000);<br/> thread1.interrupt();<br/> }catch (InterruptedException e){<br/> e.printStackTrace();<br/> }<br/> }<br/> }<br/> class TheThread extends Thread{<br/> public void run() {<br/> super.run();<br/> for (int i = 0; i < 10; i++) {<br/> if(this.interrupted()){<br/> break;<br/> }<br/> System.out.println(Thread.currentThread().getName() + ":" + i);<br/> }<br/> }<br/> }
注意,如果在TheThread类里加入catch InterruptException的话,可能会导致interrupt被捕获,而绕过if(this.interrupted())的判断而无法终止线程。
6. 等待和通知
线程等待:当前线程就处于等待状态,直到其他线程调用了notify()方法,线程才会继续执行
public final void wait() throws InterruptedException
线程通知:
public final native void notify()
注意:在notify()方法后,当前线程不会马上释放该对象锁,要等到执行notify()方法的线程将程序执行完,也就是退出同步代码块中。
package wait.notify; public class ThreadWaitNotifyTest {<br/> final static Object object=new Object();<br/> public static class T1 extends Thread{<br/> public void run(){<br/> System.out.println(System.currentTimeMillis()+": T1 start");<br/> synchronized (object){<br/> try {<br/> System.out.println(System.currentTimeMillis()+": T1 wait");<br/> object.wait();<br/> } catch (InterruptedException e) {<br/> e.printStackTrace();<br/> }<br/> }<br/> System.out.println(System.currentTimeMillis()+": T1 end");<br/> }<br/> }<br/> public static class T2 extends Thread{<br/> public void run(){<br/> System.out.println(System.currentTimeMillis()+": T2 start");<br/> synchronized (object){<br/> System.out.println("T2 synchonized code start.");<br/> object.notify();<br/> try {<br/> Thread.sleep(2000);<br/> } catch (InterruptedException e) {<br/> e.printStackTrace();<br/> }finally{<br/> System.out.println("T2 synchonized code end.");<br/> } }<br/> try {<br/> Thread.sleep(2000);<br/> } catch (InterruptedException e) {<br/> e.printStackTrace();<br/> }<br/> System.out.println(System.currentTimeMillis()+": T2 end");<br/> }<br/> }<br/> public static void main(String[] args){<br/> Thread thread1=new T1();<br/> Thread thread2=new T2();<br/> thread1.start();<br/> thread2.start();<br/> }<br/> }
输出结果:
7. 线程优先级
高优先级的线程将会获得更多的CPU资源。一共分为10个优先级。
public final void setPriority(int newPriority)
源码分析:
public final void setPriority(int newPriority) {<br/> ThreadGroup g;<br/> checkAccess();<br/> if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {<br/> throw new IllegalArgumentException();<br/> }<br/> if((g = getThreadGroup()) != null) {<br/> if (newPriority > g.getMaxPriority()) {<br/> newPriority = g.getMaxPriority();<br/> }<br/> setPriority0(priority = newPriority);<br/> }<br/> }
public final static int MIN_PRIORITY = 1;<br/> public final static int NORM_PRIORITY = 5;<br/> public final static int MAX_PRIORITY = 10;
可见线程最高优先级为10, 最低为1, 默认为5.
当设定的newPriority高于该线程组ThreadGroup的最高Priority时,只能分配该线程组的最高Priority
8. 守护线程
类似守护进程,Java存在两种线程:用户线程和守护线程。它是一种特殊线程,执行的是一种后台服务,当一个系统中不存在非守护线程的时候,守护线程会自己销毁。典型的守护线程:JVM的垃圾回收线程。
public final void setDaemon(boolean on)
示例:
public class Main {<br/> public static void main(String[] args) throws InterruptedException {<br/> TheThread theThread=new TheThread();<br/> theThread.setDaemon(true);//设置守护线程<br/> theThread.start();<br/> Thread.sleep(5000);<br/> System.out.println("全都退出啦");<br/> }<br/> public static class TheThread extends Thread{<br/> public void run(){<br/> int i = 0;<br/> while (true){<br/> i++;<br/> System.out.println(Thread.currentThread().getId()+":"+i);<br/> try {<br/> Thread.sleep(2000);<br/> } catch (InterruptedException e) {<br/> e.printStackTrace();<br/> }<br/> }<br/> }<br/> }<br/> }
源码分析:
设置线程为用户线程(user thread)或守护线程(daemon thread),当剩余运行的线程均为守护线程时,JVM会退出。
public final void setDaemon(boolean on) {<br/> checkAccess();<br/> if (isAlive()) {<br/> throw new IllegalThreadStateException();<br/> }<br/> daemon = on;<br/> }
其中checkAccesss()方法如下:
public final void checkAccess() {<br/> SecurityManager security = System.getSecurityManager();<br/> if (security != null) {<br/> security.checkAccess(this);<br/> }<br/> }
该方法用于判断当前运行的线程是否有修改此线程的权限。
而public final native boolean isAlive();用于判断该线程是否处于alive状态,即该线程是否已经start,且没有die。
当isAlive的话就会抛出IllegalThreadStateException异常。
所以,设置守护线程的方法,逻辑就是先判断当前线程是否有修改的权限,再判断是否处于alive状态,如果不处于alive状态,则根据boolean变量on的值更改它的状态,即true:设为daemon线程,false:设为user线程。