zoukankan      html  css  js  c++  java
  • java多线程--实现Runnable接口

    package unit8;
    
    import java.applet.Applet;
    import java.awt.Label;
    import java.awt.TextField;
    
    public class TestRunnable extends Applet implements Runnable{
        Label prompt1 = new Label("The first thread:");
        Label prompt2 = new Label ("The second thread:");
        TextField threadFirst = new TextField(28);
        TextField threadSecond = new TextField(28);
        Thread thread1,thread2;
        int count1=0,count2=0;
        public void init(){
            add(prompt1);
            add(threadFirst);
            add(prompt2);
            add(threadSecond);
        }
        public void start(){
            //创建线程对象,具有当前类的run方法,并用字符串指定线程对象的名字
            thread1 = new Thread(this,"FirstThread");
            thread2 = new Thread(this,"SecondThread");
            thread1.start();
            thread2.start();
        }
        public void run(){
            String currentRunning;
            while(true){
                try{
                    Thread.sleep((int)(Math.random()*3000));
                }catch (InterruptedException e) {
                    // TODO: handle exception
                }
                currentRunning = Thread.currentThread().getName();
                if(currentRunning.equals("FirstThread")){
                    count1++;
                    threadFirst.setText("线程1调用次数:"+count1);
                }else if(currentRunning.equals("SecondThread")){
                    count2++;
                    threadSecond.setText("线程2调用次数:"+count2);
                }
            }
        }
    }

    通过实现Runnable接口来实现所线程,具体实现run方法,这样当主程序sleep的时候就会执行子线程,这里的子线程都是Thread类的实例对象。

  • 相关阅读:
    P1772 [ZJOI2006]物流运输
    P4290 [HAOI2008]玩具取名
    P1859 不听话的机器人
    P1841 [JSOI2007]重要的城市
    P2182 翻硬币
    P1908 逆序对(归并排序)
    P1010 幂次方(分治)
    P3386 【模板】二分图匹配
    P2158 [SDOI2008]仪仗队
    P1582 倒水(贪心 + lowbit)
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/5791496.html
Copyright © 2011-2022 走看看