多线程学习笔记

多线程

package thread;

public class ThreadTest1 extends Thread {
    @Override
    public void run() {//重写run方法
        for (int i = 0; i < 200; i++) {
            System.out.println("我爱学习"+i);
        }
    }

    public static void main(String[] args) {
        ThreadTest1 test1 = new ThreadTest1();//创建一个线程对象
        test1.start();//开启线程
        for (int i = 0; i < 1000; i++) {
            System.out.println("我想睡觉"+i);//方法的处理,由CPU决定
        }
    }
}

一般使用Runnable的实现类来运用线程,因为一个对象可以运行多个线程。

package thread;

public class ThreadTest03 implements Runnable {
    private  int ticketnums=10;
    @Override
    public void run() {
        while (true){
            if (ticketnums<=0){
                break;//判定跳出循环的条件
            }
            try {
                Thread.sleep(200);//模拟延时
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketnums--+"张票。");
        }
    }

    public static void main(String[] args) {
        ThreadTest03 test03 = new ThreadTest03();//实例化Runnable接口实现类
        new Thread(test03,"jack").start();//启动线程,开始分配工作。
        new Thread(test03,"lucy").start();
        new Thread(test03,"merry").start();
    }
}

龟兔赛跑

package thread;

public class Demo01 implements Runnable {
    private static String winner;
    @Override
    public void run() {
        for (int i = 0; i <=100; i++) {
            /*if (Thread.currentThread().getName().equals("兔子")&&i%50==0){
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }*/
            boolean flag=gameOver(i);
            if (flag){
                break;
            }
            System.out.println(Thread.currentThread().getName()+"跑了"+i+"米。");
        }

    }
    private boolean gameOver(int meter){
        if(winner!=null){
            return true;
        }{
            if (meter>=100){
                winner=Thread.currentThread().getName();
                System.out.println("winner is"+winner);
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Demo01 test04 = new Demo01();
        new Thread(test04,"兔子").start();
        new Thread(test04,"乌龟").start();
    }
}

你可能感兴趣的:(学习,java,笔记,jvm)