您的位置:首页 > 其它

线程简介--单利模式饿汉式和懒汉式

2013-12-02 20:39 330 查看
1/创建线程:类继承Thread类复写Runnable的run()方法。start()作用:调用run方法、开启线程。只有调用Strat()方法才能开启线程。

2/线程的的状态:创建、运行、阻塞、死亡四种状态。注:线程的阻塞状态结束之后不一定会立刻执行,该线程需要取得CPU的执行权(意思:具备运行资格,但是没有执行权)。

3/j第二种创建线程的方法:定义类实现Runnable接口,复写Runnable接口的run()方法,创建Thread对象,并将实现Runnable类的对象作为创建Thread对象构造函数的参数。

4/实现Runnable接口可以实现资源共享。

5/停止线程的唯一方法是该线程的run()方法结束(stop()已经过时)。

6/当线处于程冻结状态时(wait(),sleep(),join()等状态时),可用线程调用interrupt()方法对冻结进行清除,此时抛出interruptException异常,然后继续执行。
//
public class Main {

/**
* @param args
*/
static int num=0;
public static void main(String[] args) {
RunnableTest runnable=new RunnableTest();
Thread thread1=new Thread(runnable);
Thread thread2=new Thread(runnable);
thread1.start();
thread2.start();
while (true) {
if(++num==60){//如果num的值为60时,flag为true,并终止循环
thread1.interrupt();//清除异常
thread2.interrupt();
//        		  runnable.setflag();//特殊情况,虽然改变了flag的值,但是并没终止线程循环
break;
}
System.out.println(Thread.currentThread().getName()+"......Main-->"+num);
}
}
}

//
public class RunnableTest implements Runnable {
boolean flag=true;
@Override
public   synchronized   void run() {

while (flag) {
try {

wait();//此时Thread1和Thread2分别处于阻状态塞,并放弃了cpu执行权

} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName()+"......exception");
flag=false;//改变flag值退出循环
}

System.out.println(Thread.currentThread().getName()+"......run");
}
}
public void setflag(){
flag=true;
}

}

7/线程死锁:一般出现在双重的同步程序同一把锁,并且不是,两个线程分别拥有的两把锁中不同的一把锁,而这两个线程分别等待对方释放锁

简单例子描述:
//主方法
main(){
//创建两个线程并启动两个线程
}

public class DemoLock implements Runnable{
Object obj=new Object();
run(){
.......

}
public synchronized  void show(){//锁是this
synchronized(obj){//锁是obj
.....
}
}
}

7/线程的单例模式

//单例模式设计

//恶汉式

class  Test
{
private final Static	Test test=new Test();
private Test(){}
public static Test getInstence(){
return test;
}
}

//懒汉式

class Test
{
private static Test test=null;
private Test(){}
public static Test getInstence(){
if(test==null){
synchronized (Test.class){
if(test=null){
test=new Test();
}
}
}
return test;
}

}
//懒汉式和饿汉式的区别:懒汉式延迟加载,但懒汉式在多线程并行访问时会出现安全问题,
//解决方法是使用同步函数,但是效率低一点(因为每个线程都要访问锁进行判断),解决方法是双重否定.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: