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("仓库管理员打开仓库");
        }

}
}

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

java基础知识 多线程的更多相关文章

  1. Java基础知识➣多线程编程(五)

    概述 Java 给多线程编程提供了内置的支持.一个多线程程序包含两个或多个能并发运行的部分.程序的每一部分都称作一个线程,并且每个线程定义了一个独立的执行路径.使用多线程也是为了充分的利用服务器资源, ...

  2. JAVA基础知识之网络编程——-网络基础(Java的http get和post请求,多线程下载)

    本文主要介绍java.net下为网络编程提供的一些基础包,InetAddress代表一个IP协议对象,可以用来获取IP地址,Host name之类的信息.URL和URLConnect可以用来访问web ...

  3. java基础知识小总结【转】

    java基础知识小总结 在一个独立的原始程序里,只能有一个 public 类,却可以有许多 non-public 类.此外,若是在一个 Java 程序中没有一个类是 public,那么该 Java 程 ...

  4. Java 基础知识总结

    作者QQ:1095737364    QQ群:123300273     欢迎加入! 1.数据类型:  数据类型:1>.基本数据类型:1).数值型: 1}.整型类型(byte  8位   (by ...

  5. Java基础知识回顾之七 ----- 总结篇

    前言 在之前Java基础知识回顾中,我们回顾了基础数据类型.修饰符和String.三大特性.集合.多线程和IO.本篇文章则对之前学过的知识进行总结.除了简单的复习之外,还会增加一些相应的理解. 基础数 ...

  6. Java基础知识总结(超级经典)

    Java基础知识总结(超级经典) 写代码: 1,明确需求.我要做什么? 2,分析思路.我要怎么做?1,2,3. 3,确定步骤.每一个思路部分用到哪些语句,方法,和对象. 4,代码实现.用具体的java ...

  7. 毕向东—Java基础知识总结(超级经典)

    Java基础知识总结(超级经典) 写代码: 1,明确需求.我要做什么? 2,分析思路.我要怎么做?1,2,3. 3,确定步骤.每一个思路部分用到哪些语句,方法,和对象. 4,代码实现.用具体的java ...

  8. Java 基础知识总结1

    作者QQ:1095737364    QQ群:123300273     欢迎加入! 1.数据类型:  数据类型:1>.基本数据类型:1).数值型: 1}.整型类型(byte  8位   (by ...

  9. 沉淀,再出发:Java基础知识汇总

    沉淀,再出发:Java基础知识汇总 一.前言 不管走得多远,基础知识是最重要的,这些知识就是建造一座座高楼大厦的基石和钢筋水泥.对于Java这门包含了编程方方面面的语言,有着太多的基础知识了,从最初的 ...

随机推荐

  1. MAC Osx PHP安装指导

    php.ini的位置 Mac OS X中没有默认的php.ini文件,但是有对应的模版文件php.ini.default,位于/private/etc/php.ini.default 或者说 /etc ...

  2. 玩转spring boot——结合redis

    一.准备工作 下载redis的windows版zip包:https://github.com/MSOpenTech/redis/releases 运行redis-server.exe程序 出现黑色窗口 ...

  3. c#比较两个数组的差异

    将DataTable中某一列数据直接转换成数组进行比较,使用的Linq,要引用命名空间using System.Linq; string[] arrRate = dtRate.AsEnumerable ...

  4. C语言中如何判断文件是否存在

    方法一:access函数判断文件夹或者文件是否存在 函数原型: int access(const char *filename, int mode); 所属头文件:io.h filename:可以填写 ...

  5. C#使用GET、POST请求获取结果

    C#使用GET.POST请求获取结果,这里以一个简单的用户登陆为例. 1. 使用GET请求获取结果 1.1 创建LoginHandler.aspx处理页面 protected void Page_Lo ...

  6. git多账号登录问题

    作者:白狼 出处:http://www.manks.top/git-multiply-accounts.html 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文 ...

  7. Oracle Standard Error 列表

    今天,我特意从网上找了一些,以及自己平时总结的,关于错误编号和说明,平时我们在写项目的时候,往往是可能会出现下面这些错误,例如:违反唯一约束,无效的会话ID,等等.希望对大家有点帮助!可以看看,如果有 ...

  8. linux-centos6.5之ssh配置

    查询\安装SSH服务 #rpm -qa |grep ssh 检查是否装了SSH包 #yum install openssh-server 没有的话,安装SSH服务 #chkconfig --list ...

  9. PHP安装

    工具 http://www.cnblogs.com/xiwang6428/p/4315049.html http://www.iteye.com/news/22672 1 安装:sudo apt-ge ...

  10. 四、可空类型Nullable<T>到底是什么鬼

    值类型为什么不可以为空 首先我们都知道引用类型默认值都是null,而值类型的默认值都有非null. 为什么引用类型可以为空?因为引用类型变量都是保存一个对象的地址引用(就像一个url对应一个页面),而 ...