zoukankan      html  css  js  c++  java
  • 线程问题以及调用

    实现线程的两种方式

    package sdfa;

    public class 线程 implements Runnable {

    @Override
    public void run() {
    // TODO Auto-generated method stub
    for (int i = 0; i <10; i++) {
    try {
    Thread.sleep(500);//休眠的时间
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println("第"+i+"次执行");
    }
    }
    public static void main(String[] args) {
    线程 x= new 线程();
    // x.run(); 实现Runnable接口调用线程启动的方法
    Thread t=new Thread(x);
    t.start();// 基础Thrend类调用线程启动的方法
    }
    }

    线程同步数组买票问题

    package sdfa;

    import java.util.ArrayList;
    import java.util.Scanner;

    public class 线程1 extends Thread {
    public static void main(String[] args) {

    ArrayList<线程1> tlist = new ArrayList<>();
    Object l = new Object();
    tlist.add(new 线程1(l));
    tlist.add(new 线程1(l));
    tlist.add(new 线程1(l));
    tlist.add(new 线程1(l));
    for (int i = 0; i < tlist.size(); i++) {
    tlist.get(i).start();
    }
    }

    // public static int a1= 10;
    private Object l;//同步锁
    public static int a = show();

    public 线程1(Object l) {
    super();
    this.l = l;
    }
    public 线程1() {
    }
    public void run() {
    // sa(show());
    sa();
    }

    public void sa() {
    while (true) {
    try {
    Thread.sleep(1000);
    synchronized (l) {
    if (a > 0) {
    a--;
    System.out.println(Thread.currentThread().getId());
    System.out.println("卖出一张票,还剩" + a + "张票");
    }
    }
    if (a == 0) {
    break;
    }

    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }

    public static int show() {
    System.out.println("请输入一个a值");
    Scanner s = new Scanner(System.in);
    int a = s.nextInt();
    return a;
    }
    }

  • 相关阅读:
    vue router
    spring web 不定参数
    spring boot添加自定义配置文件
    IntelliJ IDEA查看方法的返回类型
    连接MySql报错->The server time zone value 'XXXXX' is unrecognized...............
    spring boot新建工程中使用mysql,com.mysql.jdbc.Driver标红
    iOS 并发编程之 Operation Queues
    数据安全基础知识总结
    登录令牌 Token 介绍
    常见加密算法
  • 原文地址:https://www.cnblogs.com/joyous-day/p/6484909.html
Copyright © 2011-2022 走看看