多线程学习笔记,runnable实现多线程及窗口卖票

Thread 窗口卖票

package com.senior.test;

public class WindowTest {


    public static void main(String[] args) {
        Window window = new Window();
        Window window1 = new Window();
        Window window2 = new Window();


        window.setName("窗口1");
        window1.setName("窗口2");
        window2.setName("窗口3");

        window.start();
        window1.start();
        window2.start();
    }

}

class Window extends Thread {

    private static int ticket = 100;

    @Override
    public void run() {
        while (true) {
            if (ticket > 0) {
                System.out.println(getName() + "售出:" + ticket);
                ticket--;
            } else {
                break;
            }
        }
    }

}

Runnable窗口卖票

package com.senior.test;

/**
 * 创建线程的方式二:实现Runnable接口
 * 1、创建一个实现Runnable接口的类
 * 2、实现类去实现Runnable中的抽象方法,run()
 * 3、创建实现类的对象
 * 4、将此对象作为参数传递到Thread类的构造器中,创建Thread对象
 * 5、通过Thread类的对象调用start():1、启动线程 2、调用当前线程的run()
 *
 * 开发中,优先选择,实现runnable接口的方式
 * 1、实现的方式没有累的单继承性的局限性
 * 2、更适合来处理多个线程有共享数据的情况
 *
 *
 */
public class RunableTest {

    public static void main(String[] args) {
        //3、创建实现类的对象
        RunThread runThread = new RunThread();
        //4、将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
        Thread thread = new Thread(runThread);
        thread.setName("线程一");
        //5、通过Thread类的对象调用start():1 启动线程 2 调用当前线程的run()-->调用了Runnable类型的target
        thread.start();

        //再启动一个线程,遍历100以内的偶数

        Thread t2 = new Thread(runThread);
        t2.setName("线程二");
        t2.start();

    }

}

class RunThread implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }

}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值