Java编程:多线程编程,守护线程,多线程同步,利用并发API
多线程简介
守护线程
守护线程是指当普通线程结束时,守护线程自动结束,如垃圾回收线程。
1.使用方法
setDaemon(true)
2.例子1
package week8_demo;
import java.util.*;
public class TestThreadDaemon {
public static void main(String args[]) {
Thread t = new MyThread_2();
//t.setDaemon(true);//没有设置t为守护线程
t.start();
System.out.println( "Main--" + new Date());
try{ Thread.sleep(500); }
catch(InterruptedException ex){}
System.out.println("Main End");
}
}
class MyThread_2 extends Thread {
public void run() {
for(int i=0; i<10; i++ ){
System.out.println( i + "--" + new Date());
try{ Thread.sleep(100); }
catch(InterruptedException ex){}
}
}
}
输出结果:
分析
主函数分别输出Main --一个时间,和Main End
在主函数结束后,线程t还没有执行完,所以继续输出。
3.对比例子
取消注释t.setDaemon(true);
输出结果
线程的同步方法1:synchronized
编译的过程将程序分为
1、取址 2、译码 3、执行 4、保存或者更复杂的过程。
如果多个线程同时进行,则可能完成执行阶段,还没有进行保存的阶段执行另一个线程,而另一个线程修改了操作情况,这样就可能造成操作的不准确保存。
package week8_demo;
class SyncCounter2
{
public static void main(String[] args){
Num num = new Num();
Thread counter1 = new Counter(num);
Thread counter2 = new Counter(num);
for( int i=0; i<10; i++ ){
num.testEquals();
try{
Thread.sleep(100);
}catch(InterruptedException e){
}
}
}
}
class Num
{
private int x=0;
private int y=0;
synchronized void increase(){ //synchronized
x++;
y++;
}
synchronized boolean testEquals(){ ////synchronized
boolean ok = (x==y);
System.out.println( x + "," + y +" :" + ok);
return ok;
}
}
class Counter extends Thread
{
private Num num;
Counter( Num num ){
this.num = num;
this.setDaemon(true);
this.setPriority(MIN_PRIORITY);
this.start();
}
public void run(){
while(true){
num.increase();
}
}
}
只有两个都是同时设置synchronized,才能保证都是ture
synchronized使用方法
wait()方法和notify()或notifyAll()方法
结合使用方法
在synchronized代码被执行期间,线程调用对象的wait()方法,会释放对象锁标志,然后进入等待状态,然后由其它线程调用notify()或者notifyAll()方法通知正在等待的线程
并发API
原子变量
包含在java.util.concurrent.atomic包中
定义
static AtomicInteger cnt = new AtomicInteger(0);
则cnt这个变量将不会存在一半还没写完,另一个线程来读的情况
参考:慕课教程