java基础知识 多线程

package org.base.practise9;

import org.junit.Test;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午9:40
* 多线程基础知识练习
*/
public class PractiseTest {

    //1,线程有四种状态,新建,运行,中断,死亡
    //2,引起中断的原因:sleep,io阻塞,wait,cpu切换线程的时候线程进入中断状态
    //3,一个线程执行完run方法,进入死亡状态, 该线程不能在调用start方法
    //4,线程死亡了,isAlive方法返回的是false
    //5,建立线程有两种方法,继承Thread类或者实现Runable接口
    //6,setPriority();方法来设置优先级,一共有十个优先级别
    //7,为了防止资源竞争产生的死锁,主要是在写数据的时候
    //8,同步方法需要挂起线程,恢复挂起的线程的地方使用wait(),notify(),notifyAll()方法
    //9,不合理
    //10,interrupt()吵醒休眠的线程
    @Test
    public void exercise1() {

        Thread left = new Hand("左手");
        Thread right = new Hand("右手");

        left.start();
        right.start();

        for(int i=1;i<=10;i++){
            System.out.println("我是主线程");
        }

//         left.setPriority();
//        if(!left.isAlive())
        {
            System.out.println("线程left死亡了吗?"+left.isAlive());
//            left.start();
        }

    }
    //12,写一个程序,模拟买票(3人排队买票,售票员只有3张5块,电影票5块一张,张某拿一张20,李某拿一张10,赵某拿一张5块)
    @Test
    public void exercise11() {

      Buyer buyer=new Buyer();
        buyer.getZhang().start();
        buyer.getLi().start();
        buyer.getZhao().start();
    }
    //11,写一个程序,有两个线程,一个做垂直上抛运动,另外一个做模仿45度的抛体运动
    public static void main(String[] args)
    {
//        MyFrame myFrame=new MyFrame();
//        myFrame.setBounds(10,10,500,500);
//        myFrame.setVisible(true);
//        myFrame.addWindowListener(new WindowAdapter() {
//            @Override
//            public void windowClosing(WindowEvent e) {
//                System.exit(0);
//            }
//        });

//        Thread t=new Thread(new Gxy());
//        t.start();

 

        People people=new People();

        people.getTeacher().start();
        people.getStudent1().setName("李福春");
        people.getStudent1().start();
        people.getStudent2().setName("何丽君");
        people.getStudent2().start();
    }

    @Test
    public void exercise13() {

        People people=new People();

        people.getTeacher().start();
        people.getStudent1().start();
        people.getStudent2().start();

    }

    @Test
    public void exercise14() {

        Worker worker=new Worker();
        worker.getSiji().start();
        worker.getBanyun().start();
        worker.getCangguan().start();
    }

}

 

package org.base.practise9;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午11:25
* To change this template use File | Settings | File Templates.
*/
public class Buyer extends Thread {

    Thread zhang=new Thread(this);
    Thread li=new Thread(this);
    Thread zhao=new Thread(this);

    TicketSeller ticketSeller=new TicketSeller();

    public Thread getZhang() {
        return zhang;
    }

    public Thread getLi() {
        return li;
    }

    public Thread getZhao() {
        return zhao;
    }

    public Buyer()
    {

    }


    @Override
    public void run() {
        if(Thread.currentThread()==zhang){
               ticketSeller.sellTicket(20);
        }else if(Thread.currentThread()==li)
        {
            ticketSeller.sellTicket(10);
        }  else  if(Thread.currentThread()==zhao)
        {
              ticketSeller.sellTicket(5);
        }
    }
}

package org.base.practise9;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午11:43
* To change this template use File | Settings | File Templates.
*/
public class Gxy implements Runnable {

    float n=0,zhen=0,fan=0,li=0;


    @Override
    public void run() {
        while (true){
            n++;
            double  i=Math.random();
            if(i<0.5){
                zhen++;
                System.out.println("正面出现的概率 "+zhen/n);
            } else if(i==0.5)
            {
                li++;
                System.out.println("正立出现的概率 "+li/n);
            } else{
                fan++;
                System.out.println("反面出现的概率 "+fan/n);
            }

            try {
                Thread.currentThread().sleep(1000);
                System.out.println("活动线程数:"+ Thread.activeCount());;
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

        }
    }
}

package org.base.practise9;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午9:41
* 线程
*/
public class Hand extends Thread {


    private String name;

    public Hand(String name) {
        this.name = name;
    }

    @Override
    public void run() {

        print();

    }

    private synchronized void print() {
        for (int i = 1; i <= 10; i++) {
            System.out.println("我是" + name + "线程");
        }


    }
}

package org.base.practise9;

import java.awt.*;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午10:30
* 油画对象
*/
public class MyCanvas extends Canvas {

    Color c;

    public MyCanvas(Color c) {
        setSize(30, 30);
        this.c = c;
    }


    @Override
    public void paint(Graphics g) {
        g.setColor(c);
        g.fillOval(0, 0, 30, 30);
    }
}

package org.base.practise9;

import java.awt.*;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午10:32
* 面板对象,内含两个球体线程,在油画上面做位移
*/
public class MyFrame extends Frame implements Runnable {

    Thread red, blue;
    MyCanvas redC, blueC;
    double t = 0;

    public MyFrame() {
        this.red = new Thread(this);
        this.blue = new Thread(this);
        redC = new MyCanvas(Color.RED);
        blueC = new MyCanvas(Color.BLUE);

        setLayout(null);
        add(redC);
        add(blueC);
        redC.setLocation(60, 100);
        blueC.setLocation(60, 100);

        red.start();
        blue.start();

    }


    @Override
    public void run() {
        while (true) {
            int vo=80;
            t+=0.2;
            if(t>20){
                t=0;
            }
            Thread thread = Thread.currentThread();
            if (thread == red) {
                /**
                 *   S=Vot-0.5gt^2
                 */
                int x = 60;
                int y = (int)(t*vo- 0.5*9.8*t*t);
                redC.setLocation(x, y);

            } else if (thread == blue) {
                /**
                 * 水平方向位移x=V0cosα·t
                 4.竖直方向位移y=V0cosα·t-(1/2)*gt^2
                 */
                int x =(int) (Math.cos(45.0d)*t*vo);
                int y =(int) (Math.cos(45d)*t*vo-0.5*9.8*t*t);
                blueC.setLocation(x, y);


            }
            try {
                thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
    }
}

package org.base.practise9;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 下午12:01
* To change this template use File | Settings | File Templates.
*/
public class People implements Runnable {


    Thread student1=new Thread(this);

    Thread student2=new Thread(this);

    Thread teacher=new Thread(this);

    public Thread getStudent1() {
        return student1;
    }

    public Thread getStudent2() {
        return student2;
    }

    public Thread getTeacher() {
        return teacher;
    }

    @Override
    public void run() {
        if(Thread.currentThread()==student1)
        {     System.out.println(student1.getName()+"在睡觉,打算睡10分钟");
            try {
                student1.sleep(10*60*1000);
            } catch (InterruptedException e) {
               System.out.println("被老师叫醒...");
            }
            System.out.println(student1.getName()+"开始听课");
            student2.interrupt();
        }else if(Thread.currentThread()==student2)
        {
            System.out.println(student2.getName()+"在睡觉,打算睡60分钟");
            try {
                student2.sleep(60*60*1000);
            } catch (InterruptedException e) {
                System.out.println("被"+student1.getName()+"叫醒...");
            }
            System.out.println(student2.getName()+"开始听课");
        }else if(Thread.currentThread()==teacher)
        {
            for(int i=1;i<=3;i++)
            {
                System.out.println("上课了");
                try {
                    teacher.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
           student1.interrupt();
        }
    }
}

package org.base.practise9;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 上午11:13
* To change this template use File | Settings | File Templates.
*/
public class TicketSeller {

    int fiveCount=3,tenCount=0,twentyCount=0;

    public  synchronized void sellTicket(int money){
        if(money==5){
            fiveCount++;
            System.out.println("给你票,钱正好");
        }else if(money==20)
        {
            while((fiveCount<3&&tenCount<1)||(tenCount>1&&fiveCount<1))
            {
                try{
                    wait();
                } catch (InterruptedException ex)
                {

                }
            }

            if(tenCount>=1&&fiveCount>=1){
                fiveCount--;
                tenCount--;
                System.out.println("收你20块,找回5块1张,10块1张");
            }else if(fiveCount>=3){
                fiveCount-=3;
                System.out.println("收你20块,找回5块3张");
            }


        }else if(money==10){
            while (fiveCount<1)
            {
                try{
                    wait();
                } catch (InterruptedException ex)
                {

                }
            }
            fiveCount--;
            tenCount++;
            System.out.println("收你10块,找回5块");

        }
        notifyAll();
    }

}

package org.base.practise9;

/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-11
* Time: 下午12:29
* To change this template use File | Settings | File Templates.
*/
public class Worker implements Runnable {


    Thread siji=new Thread(this);

    Thread banyun=new Thread(this);

    Thread cangguan=new Thread(this);


    public Thread getSiji() {
        return siji;
    }

    public Thread getBanyun() {
        return banyun;
    }

    public Thread getCangguan() {
        return cangguan;
    }

    @Override
    public void run() {

        Thread thread=Thread.currentThread();

        if(thread==siji){

            try {
                banyun.join();
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

            System.out.println("司机开始工作");

        } else  if(thread==banyun)
        {
            try {
                cangguan.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("搬运工开始工作");
        }  else if(thread==cangguan)
        {
            System.out.println("仓库管理员打开仓库");
        }

    }
}

通过练习,熟悉了线程的基本操作和概念,温故而知新。

转载于:https://www.cnblogs.com/snidget/p/3594887.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/575565.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

最新版的SSM框架spring5.0搭建教程(附源码)

<p>用SSM框架已经有一段时间了&#xff0c;但都没有完整地搭建过一次工程。前段时间比较有时间就自己试着搭建了一下&#xff0c;差不多都是用的最新的spring版本了&#xff0c;然后就在这个基础上做了很多的实验测试。最近想着还是记录一下整个搭建的过程&#xff0c;以…

node.js 针对不同的请求路径(url) 做出不同的响应

边看这个边写的: http://wenku.baidu.com/link?urlC4yLe-TVH6060u_x4t34H3Ze8tjoL7HjJaKgH-TvHnEYl-T_gAMYwhmrCeM0Ji59WBPSkoEXPTWk8dPIZVpbFg_by_gN6DJNGYfjlFuYxE_ 上篇文章讲到了浏览器中访问 http://127.0.0.1:8888/ 输出 "hello world", 但是实际当中, 用户访…

MyBatis 为什么需要通用 Mapper ?

版权声明&#xff1a;版权归博主所有&#xff0c;转载请带上本文链接&#xff01;联系方式&#xff1a;abel533gmail.com https://blog.csdn.net/isea533/article/details/83045335 </div>在早期项目文档中有过类似主题的内容…

Oracle教程-安装、结构(一)

本文安装的是Oracle中的11G版本一、 将文件win32_11gR2_database_1of2.zip和win32_11gR2_database_2of2.zip解压。注意&#xff1a;这两个文件解压到同一个目录下&#xff0c;即&#xff1a;将Components目录合并到一起二、 双击“setup.exe”&#xff0c;弹出以下安装向导。去…

SpringBoot视频教程

SpringBoot视频教程 百度云 置顶 2018年08月02日 11:56:26 SoXiaTea 阅读数 8811 SpringBoot视频教程 百度云 史上最全最精辟的SpringBoot视频教程 B站视频地址 https://www.bilibili.com/video/av33985898 百度云保存地址 全网最实用1.5版本SpringBoot教程 链接&#xf…

[041] 微信公众帐号开发教程第17篇-应用实例之智能翻译

内容概要 本篇文章为大家演示怎样在微信公众帐号上实现“智能翻译”&#xff0c;本例中翻译功能是通过调用“百度翻译API”实现的。智能翻译是指用户随意输入想要翻译的内容&#xff08;单词或句子&#xff09;&#xff0c;系统能自己主动识别用户採用的语言&#xff0c;并将其…

读书,上学,上名校!!!!!

摘自读者上的一篇文章 “龟兔赛跑&#xff0c;如果兔子一直在跑&#xff0c;会发生什么....” 原文作者&#xff1a;王凤 一 念高中时&#xff0c;常听班主任提起一个学姐。她几乎不跟周围的人说话&#xff0c;也没什么朋友&#xff0c;直到高考&#xff0c;她考进全省前10名…

思维模式

人生是可以设计的&#xff0c;生涯是可以规划的&#xff0c;幸福是可以准备的。现在就可以开始。在你穷的时候&#xff0c;要少在家里&#xff0c;多在外面。在你富有的时候&#xff0c;要多在家里&#xff0c;少在外面。这就是生活的艺术。穷得时候&#xff0c;钱要花给别人&a…

钉钉上手体会:阿里实用主义的野望

钉钉出自阿里之手&#xff0c;而阿里是电商出身&#xff0c;在移动办公和协同办公方面不算老司机&#xff0c;但钉钉却凭借阿里的背书声称拿下了这个市场的最大份额&#xff0c;甚至超过后面9名的总和&#xff08;数据来源为钉钉官网发布的《2018中国智能移动办公行业趋势报告》…

WAF与IPS的区别总结

谁是最佳选择&#xff1f; Web应用防护无疑是一个热门话题。由于技术的发展成熟和人们对便利性的期望越来越高&#xff0c;Web应用成为主流的业务系统载体。在Web上“安家”的关键业务系统中蕴藏的数据价值引起攻击者的青睐&#xff0c;网上流传的Web漏洞挖掘和攻击工具让攻击的…

企业微信:腾讯的“佛系”办公江湖

、 在协同办公领域&#xff0c;近几年来移动办公伴随着智能手机蓬勃发展起来&#xff0c;特别是腾讯和阿里的入场&#xff0c;改变了业内中小微市场群雄逐鹿的大混战态势&#xff0c;开启了楚汉争霸的局面。相比于钉钉强势的攻城略地&#xff0c;企业微信的“淡定”让人感觉很佛…

for语句中声明变量

在C语言中,局部变量应该在函数的可执行语句之前定义,但在C中变量可在任何语句位置定义,只要允许程序语句的地方,都允许定义变量。 在C99标准中C同C一样允许在for循环语句中定义变量。并且这个变量作用域被限定在for循环中,在for循环外就成为了未定义变量&#xff08;C也是&…

Eclipse安装STS插件

Eclipse安装STS插件 1、下载STS插件 地址&#xff1a;https://spring.io/tools/sts/all/ 最上面是已经安装好STS插件的Eclipse软件&#xff0c;可以点击上图红框中的“previous Spring Tool Suite™ versions”&#xff0c;查看其它版本的Eclipse。下面依次为更新文件、更新站…

转载:CSS hack技巧大全

原文地址&#xff1a;http://www.duitang.com/static/csshack.html part2 —— CSS hack技巧大全 ——作者&#xff1a;吴雷君兼容范围&#xff1a;IE:6.0&#xff0c;FireFox:2.0&#xff0c;Opera 10.0&#xff0c;Sarari 3.0&#xff0c;Chrome参考资料&#xff1a; 各游览器…

Eclipse安装STS插件并解决安装缓慢问题

原 Eclipse安装STS插件并解决安装缓慢问题 2018年11月20日 10:22:29 MyronCham 阅读数 1198 标签&#xff1a; sts 更多 个人分类&#xff1a; 开发工具 Eclipse安装springsource Tool Suite&#xff08;STS)插件&#xff1a;

TextBox控件中只输入整数的几种方法

方法一. if(e.KeyChar!8&&!Char.IsDigit(e.KeyChar)&&e.KeyChar!.) { e.Handled true; } 方法二: if ((e.KeyChar < 48 || e.KeyChar > 57) && (e.KeyChar ! 8) &&e.KeyChar!.) { e.Handled true; } 方法三:if (!Cha…

InvalidCharacterError: Failed to execute 'setAttribute' on 'Element': ')' is not a valid

问题描述&#xff1a; 在webStorm开发angular应用时候 或者vue等&#xff0c;页面没内容&#xff0c;浏览器控制台报错&#xff0c;报诸如题目类似的错误&#xff0c;无误定位性。没找到问题。 查错过程&#xff1a; 1、检查程序有误明显异常 2、检查依赖是否正常 3、检查对应…

Sencha touch API

Sencha touch API http://docs.sencha.com/touch/2.3.1/#!/guide/getting_started 转载于:https://www.cnblogs.com/wuyida/p/6300382.html

eclispe Springboot项目修改html,jsp 页面不能及时刷新

Springboot静态文件不更新的解决办法,以及Springboot实现热部署 正确答案是把菜单 Project > Build Automatically 。&#xff08;之前不知道怎么手瞎把这个给去了&#xff09;。否则再怎么设置缓存&#xff0c;devtools都是白瞎。

Java后台生成NO2016012701(代码+年月日+流水号)这样的流水编号

记录今日较大的点。 参考文章&#xff1a; https://blog.csdn.net/weixin_44538107/article/details/87740611 https://blog.csdn.net/jianqiangdexiaohai/article/details/81240176 项目过程中需要自动生成编号&#xff0c;不在数据库生成&#xff0c;而是在后台代码生成&am…