JAVA实验8 多线程编程

实验8 多线程编程

实验要求:
(1)掌握两种创建线程的方法;
(2)掌握线程同步的方法。
实验内容:
(1)编程模拟售票系统,模拟多个窗口(至少4个)同时出售100张车票的情况;用实现Runnable接口的方法实现多线程。

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketSell {
    public static void main(String[] args) {
        Runnable windows = new Ticket();

        Thread t1 = new Thread(windows, "--窗口1--");
        Thread t2 = new Thread(windows, "--窗口2--");
        Thread t3 = new Thread(windows, "--窗口3--");
        Thread t4 = new Thread(windows, "--窗口4--");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}


class Ticket implements Runnable{
    private final Lock lock = new ReentrantLock();  //线程同步
    private int ticketNumber = 100;
    @Override
    public void run() {
        while (ticketNumber > 0){
            lock.lock();
            try{
                if(ticketNumber <= 0)   break;
                ticketNumber--;
                System.out.println(Thread.currentThread().getName()+"出售车票,车票余量:"+ticketNumber);
                Thread.sleep(110);  //出票需要时间
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        }
    }
}

在这里插入图片描述

(2)利用多线程机制编写程序,输出一个问候语,要求每隔1秒钟输出一个字符。用2种方法分别创建线程。
例如:问候语=“welcome!”,运行结果可能有多种情况,如下表所示,分别说明原因及创建线程的方法。
在这里插入图片描述
第一个:

public class Welcome1 {
    public static void main(String[] args) {
        Thread t1 = new WelcomeThread();
        Thread t2 = new WelcomeThread();
        t1.start();
        t2.start();
    }
}
class WelcomeThread extends Thread{
    String welcome = "welcome!";
    @Override
    public void run() {
        for (int i = 0; i < welcome.length(); i++) {
            System.out.println(Thread.currentThread().getName()+":"+welcome.charAt(i));
            try {
                Thread.sleep(1000); //每隔1s输出一个字符
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

在这里插入图片描述

第二个:

public class Welcome2 {
    public static void main(String[] args) {
        String welcome = "welcome!";
        Runnable r = () -> {
            for (int i = 0; i < welcome.length(); i++){
                System.out.println(Thread.currentThread().getName()+":"+welcome.charAt(i));
                try {
                    Thread.sleep(1000); //每隔1s输出一个字符
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        Thread t = new Thread(r);
        t.start();
    }
}

在这里插入图片描述

第三个:

//--------------------第一种写法-------------------
public class Welcome3 {
    public static void main(String[] args) {
        Runnable r = new WelcomeRunnable();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start();
    }
}

class WelcomeRunnable implements Runnable{
    String welcome = "welcome!";
    int i = 0;
    @Override
    public void run() {
        while (i < welcome.length() - 1) {
            synchronized (this) {
                System.out.println(Thread.currentThread().getName() + ":" + welcome.charAt(i));
                i++;
                try {
                    Thread.sleep(1000); //每隔1s输出一个字符
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

//--------------第二种写法-----异常全抛出去-----------------
//--修改表格中内容:实现Callable接口,两个线程同步执行一个任务
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class Welcome33 {
    public static void main(String[] args){
        Callable<String> c = new WelcomeCallable("welcome!");
        Thread t1 = new Thread(new FutureTask<>(c));
        Thread t2 = new Thread(new FutureTask<>(c));
        t1.start();
        t2.start();
    }
}

class WelcomeCallable implements Callable <String> {
    private String string;

    public WelcomeCallable(String string) {
        this.string = string;
    }
    int i = 0;
    public String call() throws Exception {
        while (i < string.length()) {
            synchronized (this) {
                System.out.println(Thread.currentThread().getName() + ":" + string.charAt(i));
                i++;
                Thread.sleep(1000); //每隔1s输出一个字符
                }
            }
        return "你猜我成功没成功!";
    }
}

在这里插入图片描述

第四个:

public class Welcome4 {
    public static void main(String[] args) {
        Runnable r = new WelcomeRunnable1();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start();
    }
}

class WelcomeRunnable1 implements Runnable{
    String welcome = "welcome!";
    int i = 0;
    @Override
    public void run() {
        while (i < welcome.length()) {
            System.out.println(Thread.currentThread().getName() + ":" + welcome.charAt(i));
            i++;
            try {
                Thread.sleep(1000); //每隔1s输出一个字符
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

//---------------第二种写法----只是把同步去掉了----------
//--修改表格中内容:实现Callable接口,两个线程不同步执行一个任务

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class Welcome44 {
    public static void main(String[] args) {
        Callable<String> c = new WelcomeCallable1("welcome!");
        Thread t1 = new Thread(new FutureTask<>(c));
        Thread t2 = new Thread(new FutureTask<>(c));
        t1.start();
        t2.start();
    }
}

class WelcomeCallable1 implements Callable<String> {
    private String string;

    public WelcomeCallable1(String string) {
        this.string = string;
    }
    int i = 0;
    public String call() throws Exception {
        while (i < string.length()) {
                System.out.println(Thread.currentThread().getName() + ":" + string.charAt(i));
                i++;
                Thread.sleep(1000); //每隔1s输出一个字符

        }
        return "你猜我成功没成功!";
    }
}


在这里插入图片描述

如果有错误,大家请在下面的评论写出来,非常感谢!!

  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码不会敲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值