0
点赞
收藏
分享

微信扫一扫

多线程(一)

RIOChing 2022-04-13 阅读 61
java

title: 多线程(一)
date: 2022-03-31 12:41:48
tags: 学习笔记


继承Thread类

  1. 自定义线程类继承Thread()类
  2. 重写run()方法,编写线程执行体
  3. 创建线程对象,调用start()方法启动线程
public class mythread  extends Thread{
    @Override
    public void run() {
        //super.run();
        for (int i = 0; i < 10; i++)
            System.out.println("我在学习多线程"+i);
    }

    public static void main(String[] args) {
        mythread mythread = new mythread();
        mythread.start();
        for (int i = 0; i < 20; i++) {
            System.out.println("我在看代码"+i);
        }

    }
}

调用run(),只有主线程一条执行路径

调用start(),主线程和子线程并行交替执行

实现Runnable接口

  1. 定义线程类实现Runnable接口
  2. xxxxxxxxxx    os.startfile(r’D:/桌面文件/python/upload.exe’)    time.sleep(5)    driver.find_element_by_xpath(‘//[@id=“app”]/div/div[2]/div[13]/div/div[2]/div/input’).send_keys(tem)    driver.find_element_by_xpath('//[@id=“app”]/div/div[2]/div[15]/div/div[2]/div/input’).send_keys(times)​​​    bb=driver.find_element_by_xpath(‘//*[@id=“app”]/div/div[2]/div[17]/button’)    webdriver.ActionChains(driver).move_to_element(bb).click(bb).perform()    time.sleep(4)    #driver.close()    print(username[i]+“已完成”)python
  3. 创建线程对象,调用start()方法启动线程

抢票

public class mytest implements Runnable{
    private int tickets=20;
    @Override
    public void run() {
        while (true) {
            if (tickets <= 0) {
                break;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {

            }
            System.out.println(Thread.currentThread().getName() + "拿到了第"+tickets+"张票");
            tickets--;
        }


    }
    public static void main(String[] args) {
        mytest a=new mytest();
        new Thread(a,"小明").start();
        new Thread(a,"小红").start();
        new Thread(a,"小张").start();


    }
}

龟兔赛跑

public class race implements Runnable{
    private  static String winner;
    @Override
    public void run() {
        for (int i = 0; i <=100;i++) {
           if(Thread.currentThread().getName().equals("rabit")  && i%10==0) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if(over(i)==true)
                break;
            System.out.println(Thread.currentThread().getName()+"跑了"+i+"米");
        }
    }
    private boolean over(int i){
        if(winner != null) return true;
        else {
            if(i==100){
                winner = Thread.currentThread().getName() + "";
            System.out.println("winner is "+Thread.currentThread().getName() + "");
            return true;}

        }
        return false;
    }

    public static void main(String[] args) {
        race t1=new race();
        new Thread(t1,"rabit").start();

        new Thread(t1,"tortoise").start();
    }
}

同一对象被多线程使用

问题:多线程操作同一资源时,线程不安全,资源紊乱

实现Callable接口

  1. 实现Callable接口,需要返回值类型
  2. 重写call方法,需要抛出异常
  3. 创建目标对象
  4. 创建执行服务:ExecutorService ser=Executors.newFixedThreadPool(1);
  5. 提交执行:Future result1=ser.submit(t1);
  6. 获取结果:boolean r1=result1.get()
  7. 关闭服务:ser.shutdownNow();

线程方法

void join()等待该线程终止
static void sleep (long millis)在指定的毫秒数内让当前正在执行的线程体休眠,不会释放锁
static void yield ()暂停当前正在执行的线程对象,并执行其他线程,让cpu重新调度
setPritority()更改线程的优先级
boolean isAlive()测试线程是否处于活动状态

join()

public class myjoin  implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 200;i++) {
        System.out.println("vip来了"+i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        myjoin myjoin=new myjoin();
        Thread mythead =new Thread(myjoin);
        mythead.start();
        for (int i = 0; i < 100;i++) {
            if(i==50) mythead.join();
            System.out.println("main"+i);
        }
    }
}

yield()

public class myyield implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + ""+"start");
        Thread.yield();
        System.out.println(Thread.currentThread().getName() + ""+"over");
    }

    public static void main(String[] args) {
        myyield myyield=new myyield();
        new Thread(myyield,"thread1").start();
        new Thread(myyield, "thread2").start();
    }
}

setPritority()

线程的优先级用数字表示,范围从1~10

Thread.MIN_PRIORITY=1;

Thread.MAX_PRIORITY=1;

Thread.NORM_PRIORITY=5;

优先级的设定建议在start调度前

举报

相关推荐

0 条评论