多线程-李兴华

来源:互联网 发布:单片机论文题目 编辑:程序博客网 时间:2024/05/23 23:43
-----线程的强制运行--------------------join()-----------------------------------


class MyThread implement Runnable{
public void run(){
  for(int i=0;i<50;i++){
   System.out.print(Thread.currentThread().getName+"运行线程的名字,i="+i)
  }
}
}


public class ThreadJoinDemo{
   public static void main(String args[]){
   MyThread mt = MyThread();//实例化Runnable子类实例
   Thread t = new Thread(mt,"线程");  //实例化Thread对象
   t.start(); //开启线程
   for (int i=0;i<50;i++){
      if(i>10){
        t.join(); //线程强制运行
      }
      System.out.println("主线程:"+i);
   }
   }


}


-----线程睡眠----------------------------Thread.sleep()--------------
线程休眠Thread.sleep(1000) 休眠1000毫秒


-----线程的中断------------------------------------------------------
一个线程可以被另一个线程中断其操作状态,使用interrupt()方法
package com.dt.compara;


class MyThread implements Runnable{
@Override
public void run() {
System.out.println("1,进入run方法");
try {
Thread.sleep(10000);
System.out.println("2,休眠结束了");
} catch (InterruptedException e) {
//e.printStackTrace();
System.out.println("3,休眠被强制终止了");
return; //返回调用的地方  不能再往下执行走了

}

System.out.println("4,run方法正常结束");
}
}


public class ThreadInterruptDemo {
public static void main(String[] args) {
MyThread mt = new MyThread();
Thread thread = new Thread(mt, "线程");
thread.start(); //启动线程 
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt(); //中断线程执行(线程正在执行休眠 中断他)
}
}
------线程优先级-----------------------------------------------------------------
优先级越高 ,越有可能先执行
package com.dt.compara;


class MyThread2 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName());
}
}
}


public class ThreadDemo {


public static void main(String[] args) {
Thread t1 = new Thread(new MyThread2(), "线程A");
Thread t2 = new Thread(new MyThread2(), "线程B");
Thread t3 = new Thread(new MyThread2(), "线程C");
t1.setPriority(Thread.MIN_PRIORITY); // 优先级最高
t2.setPriority(Thread.MIN_PRIORITY); // 优先级最低
t3.setPriority(Thread.MAX_PRIORITY); // 优先级一般
t1.start();
t2.start();
t3.start();
System.out.println(Thread.currentThread().getPriority());//主线程的优先级


}


}
--------线程的礼让------------yield()-------------------------------------------------
run方法里面使用 Thread.yield();


-----------------------------------------------------------同步死锁---------------------
同步代码块
:代码块分为四种:普通块、构造块、静态块,
--同步代码块(synchronized)
synchronized(同步对象){
需要同步的代码;
}


---同步方法:
synchronized 方法返回值 方法名称(参数列表){


}




------------------同步存在的问题----------------------
过多的同步会产生死锁
所谓死锁: 是指两个或两个以上的进程在执行过程中,
因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。
关键点:1)两个以上的进程
            2)争夺共享的资源
            3)它们各自不释放手中资源,除非有外力协助


  因此避免死锁的一个通用的经验法则是:当几个线程都要访问共享资源A、B、C时,保证使每个线程都按照同样的顺序去访问它们,比如都先访问A,在访问B和C。 
  此外,Thread类的suspend()方法也很容易导致死锁,因此这个方法已经被废弃了.
原创粉丝点击