Java 多线程的实现方式(Runnable)

通过Runnable 实现run接口实现多线程

package com.xinjue.test;

/**
 * Runnable 用法  和加锁的方式
 * @author Administrator
 *
 */
class MyThread1 implements Runnable{  
    private int a =10;  
    public void run(){  
        for(int i = 0; i<500; i++){ 
        	synchronized (this) { //票数上万就可以看到实际的作用范围    可以通过设置 a的值来看实际的效果
        		if(this.a>0){
                    System.out.println(Thread.currentThread().getName() + "卖票---->" + (this.a--));  
        		} 
			}
             
        }
        /*while (a >0) {
            synchronized (ob) { //票数上万就可以看到实际的作用范围    可以通过设置 a的值来看实际的效果
                if(a>0){
                    System.out.println(Thread.currentThread().getName() + "卖票---->" + a);
                    a--;
                } else {
                    System.out.println(Thread.currentThread().getName() + "票卖完了!");
                }
            }
        }*/  
    }  
} 
public class Runnable_ {  

    public static void main(String[] args) {  
        // 设计三个线程  
        MyThread1 mt = new MyThread1();  
        Thread t1 = new Thread(mt, "1号窗口");  
        Thread t2 = new Thread(mt, "2号窗口");  
        Thread t3 = new Thread(mt, "3号窗口");  
        t1.start();  
        t2.start();  
        t3.start();  
    }  
}

posted @   码奴生来只知道前进~  阅读(52)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示