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;
    }
    }

  • 相关阅读:
    数据表管理admin
    HDU 5057
    HDU 5056
    HDU 6035(树形dp)
    CodeForces 586D
    Codeforces 940D
    CodeForces 820C
    TOJ4114(活用树状数组)
    2017CCPC中南地区赛 H题(最长路)
    CodeForces 544C (Writing Code)(dp,完全背包)
  • 原文地址:https://www.cnblogs.com/joyous-day/p/6484909.html
Copyright © 2011-2022 走看看