⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 k.txt

📁 清华本科全套java课件 经典不用多说
💻 TXT
字号:
----------------------k1----------------------
import java.io.*;

public class a        // Application主类
{
  public static void main(String args[])   //输入一个整数参数(素数检查上限)
  {	
    if(args.length<1)
    {   
      System.out.println("请输入一个命令行参数");	
      System.exit(0);
    }	
                      //创建用户Thread子类的对象实例,使其处于NewBorn状态
    primeThread getPrimes = new primeThread(Integer.parseInt(args[0]));
    getPrimes.start();            //启动用户线程

    while( getPrimes.isAlive() )
    {
      System.out.println("Counting the prime number...");//说明主线程在运行
      try
      {
        Thread.sleep(500);//使主线程挂起指定毫秒数,以便用户线程取得	
      }					  //控制权,sleep是static的类方法
      catch(InterruptedException e)//sleep方法可能引起的异常,必须加以处理
      {
        return;	
      }
    }//while循环结束
    System.out.println("线程已停止 ,请按回车结束主线程");	
    try
    {
      System.in.read();	
    }
    catch(IOException e) {}
  }  //main方法结束
}    //主类结束

class primeThread extends Thread   //创建Thread子类,在其run()中实现子线程操作
{              
  int m_nCircleNum;		//循环的上限

  primeThread(int Num)	{	//构造函数	
    m_nCircleNum = Num;	
  }
  public void run() {   //继承并重载父类Thread的run()方法
    int number = 3;
    boolean flag = true;
    while(true)	//无限循环
    {
       for(int i=2;i<number;i++)	        //检查number是否为素数
         if( number%i ==0)   flag = false;
       if(flag)					
          System.out.println(number+"是素数");
       else
          System.out.println(number+"不是素数");
       number++;		//修改number的数值,为下一轮素数检查做准备
       if ( number > m_nCircleNum ) 	//到达要求检查数值的上限
       {
         return;			//结束run()方法,结束线程
       }
       flag = true;		//恢复flag,准备检查下一个numb
       try
       {	//一轮检查之后,暂时休眠一段时间
          sleep(300);
       }
       catch(InterruptedException e)
       {
         return;
       }
    }                 //while循环结束
  }                     //run()方法结束
}//primeThread类定义结束

-----------------------------------k2-------------------------------
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class a extends Applet implements Runnable{
  Thread thread1,thread2;
  AudioClip  m_audio ;
  Image[] m_Images= new Image[18] ;
  int totalImages = 18; //图片序列中的图片总数
  int currentImage = 0;	//当前时刻应该显示的图片序号
  boolean t1_stop = false ;
  boolean t2_stop = false ;
  Button b1 = new Button("stop1");
  Button b2 = new Button("stop2");
  Panel p1 = new Panel();

  public void init() {
    setFont(new Font("TimesRoman",Font.PLAIN,20));
    setLayout(new BorderLayout());
    p1.add(b1);  b1.addActionListener(new ActionListener()  {
                     public void actionPerformed(ActionEvent e) {
                        t1_stop = true ; m_audio.stop(); } } );
    p1.add(b2);  b2.addActionListener(new ActionListener()  {
                     public void actionPerformed(ActionEvent e) {
                        t2_stop = true ;  } } );
    add(p1,BorderLayout.SOUTH);

    m_audio  = getAudioClip(getCodeBase(), "sound/music1.wav");
    for(int i=0;i<=totalImages-1;i++)
    m_Images[i] = getImage(getDocumentBase(),"images/img"+ i + ".gif");
    
  }

  public void start() {
      thread1 = new Thread(this,"t1");
      thread2 = new Thread(this,"t2");
      thread1.start();
      thread2.start();
  }

  public void run() {
    String s = Thread.currentThread().getName();
    System.out.println("----------"+ s + "----");
    if (s.equals("t1")){
      while(!t1_stop) {
        m_audio.play();
        try{
          Thread.sleep(300000);
        }catch(InterruptedException e){}
      }
    }
    else if (s.equals("t2")){
      while(!t2_stop){
        repaint();
        try{
          Thread.sleep(50);
        }catch(InterruptedException e){}
      }
    }
  }

  public void paint(Graphics g)  {
    g.drawImage(m_Images[currentImage],75,50,this);	//显示当前序号的图片
    currentImage = ++currentImage % totalImages; //计算下一个应显示图片的序号
  }

}  // end of applet

//---------------------------k3----线程互斥 加锁---------------

import java.io.* ;
class a {
  public static void main(String[] args) {
    Sync sync2000 = new Sync() ;
    T1 t1 = new T1("t1",sync2000);
    T2 t2 = new T2("t2",sync2000);
    t1.start();
    t2.start();
    while(t1.isAlive() || t2.isAlive()) {
       if (t1.isAlive()) System.out.println("---------- t1 is Alive");
       if (t2.isAlive()) System.out.println("========== t2 is Alive");
       try{
        Thread.sleep(5000);
       }catch(Exception e){}
    }  
       System.out.println(" end of all threads ");
  }
}

class T1 extends Thread {
  Sync syn  ;
  T1(String name,Sync s){
    super(name);
    syn = s ;
  }
  public void run(){
    System.out.println(getName() + "  getx()=  " + syn.getx());
  }
}

class T2 extends Thread {
  Sync syn  ;
  T2(String name,Sync s){
    super(name);
    syn = s ;
  }
  public void run(){
//    System.out.println(getName() + "   getx()=  " + syn.getx());
//    System.out.println(getName() + "   gety()=  " + syn.gety());
    System.out.println(getName() + "   getz()=  " + syn.getz());
  }
}

class Sync {
  BufferedReader stdin = new BufferedReader(     
               new InputStreamReader(System.in) );
  int m=0 ;
  public synchronized int getx() {
    int x ;
    System.out.println(Thread.currentThread().getName() +
                       "  enter getx()-critical");
    try{
      stdin.readLine();
    }catch(Exception e){}
    x = m ;  x = x + 1 ;  m = x ;  
    return m ;
  }

  public synchronized int gety() {
    int y ;
    System.out.println(Thread.currentThread().getName() +
                       "  enter gety()-critical");
    try{
      stdin.readLine();
    }catch(Exception e){}
    y = m ;  y = y + 1 ;  m = y ;  
    return m ;
  }

  public int getz() {
    int z ;
    System.out.println(Thread.currentThread().getName() +
                       "  enter getz()");
    synchronized(this){
      System.out.println(Thread.currentThread().getName()+
                       " enter critical");
      try{
        stdin.readLine();
      }catch(Exception e){}
      z = m ;  z = z + 1 ;  m = z ;  
      return m ;
    }
  }
}

//--------------------k4  生产者/消费者----------------------
import java.util.*;
class IntQueue extends Vector{
  int m_size ;
  IntQueue(int capacity){
    m_size = capacity ;
  }
  
  boolean isFull(){
    return size()==m_size ;
  }
  synchronized void qIn(int x){
    while(isFull()){
      try{
        this.wait();
      }catch(InterruptedException e){}
    }
    add(new Integer(x));
    this.notify();
  }

  synchronized int qOut(){
    while(isEmpty()){
      try{
        this.wait();
      }catch(InterruptedException e){}
    }
    this.notify();
    return ((Integer)remove(0)).intValue();
  }
}

class Producer extends Thread{
  IntQueue pq ;
  
  Producer(IntQueue q){
    pq = q ;
  }
  public void run(){
    int i ;
    for (int j=1;j<=10;j++){
      i = (int)(Math.random()*10);
      pq.qIn(i) ;
      System.out.println("  produced :   " +i );
      try{
        sleep( (int)(Math.random()*100) );  
      }catch(InterruptedException e){}
    }
  }
}   

class Consumer extends Thread{
  IntQueue cq ;
  int fromq ;
  Consumer(IntQueue q){
    cq = q ;
  }
  public void run(){
    for (int j=1;j<=10;j++){
      fromq = cq.qOut() ;
      System.out.println("         consumed :   " +fromq );
      try{
        Thread.sleep( (int)(Math.random()*100) );  
      }catch(InterruptedException e){}
    }
  }
}  

class a {
  public static void main(String[] arge){
    IntQueue testq = new IntQueue(5); 
    Producer pro = new Producer(testq);
    Consumer con = new Consumer(testq);
    con.start();
    pro.start();
  }
}    

//---------------k5 ----------------------------------

import java.io.* ;
class a {
  public static void main(String[] args) {
    Sync sync2000 = new Sync() ;
    T1 t1 = new T1("t1",sync2000);
    T2 t2 = new T2("t2",sync2000);
    t2.start();
    t1.start();
    try{
      t1.join();
      t2.join();
    }catch(Exception e){};
    System.out.println(" end of all threads ");
  }
}

class T1 extends Thread {
  Sync syn  ;
  T1(String name,Sync s){
    super(name);
    syn = s ;
  }
  public void run(){
      for(int i=1;i<=10;i++){
        synchronized(syn){
          while(syn.x!=0){
            try{syn.wait();}catch(Exception e){}
          }
          syn.x=i;
          syn.notify();
        }
      }
  }
}  //end of class T1

class T2 extends Thread {
  Sync syn  ;

  T2(String name,Sync s){
    super(name);
    syn = s ;
  }

  public void run(){
    while(true){
      synchronized(syn){
        while(syn.x==0){
          try{syn.wait();}catch(Exception e){}
        }
        System.out.println(syn.x);
        if(syn.x==10) return;
        syn.x=0;
        syn.notify();
      }
    } //end of loop
  }
}

class Sync {
  int x=0 ;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -