CoreJava day12笔记

来源:互联网 发布:淘宝手机如何删除评价 编辑:程序博客网 时间:2024/04/29 05:26

Core Java
班级:SD0607 & XDSD0601
主讲:胡鑫喆
总结:应越

day12

多线程

 任务的执行是宏观上的并行,微观上的串行.
 由操作系统来进行进程的调度
 进程和线程的区别:
 <1>线程是轻量级的进程
 <2>线程与线程间是数据共享的,而进程与进程间数据不共享
 
 Java支持多线程,主方法叫做主线程
 
 实现一个线程的两种方式:
 <1>继承Thread类
  class MyThread extends Thread{
   public void run(){
    //...
   }
  }
  使用时
  Thread t =new MyThread();
  t.start();
 <2>实现Runnable接口
  class MyThread implements Runnable{
   public void run(){
    //...
   }
  }
  使用时 
  Rannable r = new MyThread();
  Thread t = new Thread(r);
  也可以写成:
  Thread t = new Thread(new MyThread());

 Thread 的一些方法:
 <1> yield() : 运行状态的线程可以调用,主动放弃CPU,回到可运行状态
 <2> setPriority(int) : 设置优先级 , 值越大优先级越高(1-10) 不建议使用
 <3> sleep(int) :括号中的时间是以纳秒为单位的
 <4> jion() :表示放弃CPU进入阻塞状态

 练习:要求写出两个线程 , 一个线程打数字1-52 , 另一个线程打字母A-Z
      打印格式为
      1
  2  
  A
  3
  4
  B
  5 
  ...当打到26时 一直打字母 直到字母打完再打数字

代码:

public class TestThread2 {
 public static void main(String[] args) {
  Thread t2=new Thread(new Target2());
  ThreadA t1=new ThreadA();
  t1.setT(t2);
  t1.start();
  t2.start();
 }
}

class ThreadA extends Thread{
 private Thread t;
 public void setT(Thread t){
  this.t=t;
 }
 public void run(){
  try{
   for(int i=1;i<=52;i++){
    if(i==27) t.join();
    System.out.println(i);
    if(i%2==0) Thread.yield();
   }
  }catch(InterruptedException e){
   e.printStackTrace(); 
  }
 }
}
class Target2 implements Runnable{

 public void run() {
  for(char a='A';a<='Z';a++){
   System.out.println(a);
   Thread.yield();
  }
 }
 
}

 

原创粉丝点击