java中的多线程小分享
1、思考:要在五个窗口卖出1000张车票,肯定是同时进行,1000张车票逐渐减少,每个窗口卖车票肯定是互不相关,你卖你的我卖我的,但是它们卖的车票却是共有的,票数就那么多,卖完了就没了,所以我们就把这个过程,用代码给它呈现出来。
2、新建工程,新建包,建一个为baidu_thread命名的类,
在建一个外部类baidufenxiag_thread,让他实现Runnable接口
以下========================================是代码
package com.baidu.my;
public class baidu_thread {
/**
* @param args
* @author 朱宏发
*/
public baidu_thread() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
baidufenxiag_thread baidufiang=new baidufenxiag_thread();
Thread th1=new Thread(baidufiang);//新建线程
th1.setName("窗口一");//给线程命名
Thread th2=new Thread(baidufiang);//新建线程
th2.setName("窗口二");//给线程命名
Thread th3=new Thread(baidufiang);//新建线程
th3.setName("窗口三");//给线程命名
Thread th4=new Thread(baidufiang);//新建线程
th4.setName("窗口四");//给线程命名
Thread th5=new Thread(baidufiang);//新建线程
th5.setName("窗口五");//给线程命名
th1.start();
th2.start();
th3.start();
th4.start();
th5.start();//调用start()方法启动线程
}
}
/**
* @baidufenxiag_thread:建立一个我把它叫baidufenxiag_thread的类让他实现Runnable接口
* @run:重写run()方法
*/
class baidufenxiag_thread implements Runnable{
private String name;//给每个线程命名
private int tick=1000;//有1000张票出售
public baidufenxiag_thread() {
//构造方法
}
public baidufenxiag_thread(String name) {
this.name=name;
}
public void run() {
test_tick();
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the tick
*/
public int getTick() {
return tick;
}
/**
* @param tick the tick to set
*/
public void setTick(int tick) {
this.tick = tick;
}
//使用synchronized同步锁方法使得tick资源不会出现负数情况
private synchronized void test_tick() {
for(int i=0;i<=1000/5;i++){
if(tick>=0){
try {
System.out.println(Thread.currentThread().getName()+"卖出后还剩:-->"+tick--);
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

3、在外部类baidufenxiag_thread 里实现 get/set 方法
eclipse的快捷键是“Alt+Shift+s”,主要用于给各个线程命名


4、最后运行结果如下图所示
