多线程 简单的实现案例

package com;

import java.io.IOException;
import java.nio.CharBuffer;

public class Demo04 {
        public static void main(String[] args) {
        /*    MyThread t1 = new MyThread();
            t1.setName("线程一");
            MyThread t2 = new MyThread();
            t2.setName("线程二");
            MyThread t3 = new MyThread();
            t3.setName("线程三");
            MyThread t4 = new MyThread();
            t4.setName("线程四");
            t1.start();
            t2.start();
            t3.start();
            t4.start();*/
            test02();
                    
        }
        
        
        
        
        public static  void test02(){
            MyThread02 thread02 = new MyThread02();
            Thread t1 = new Thread(thread02);
            t1.setName("线程一");
            Thread t2 = new Thread(thread02);
            t2.setName("线程二");
            Thread t3 = new Thread(thread02);
            t3.setName("线程三");
            Thread t4 = new Thread(thread02);
            t4.setName("线程四");
            t1.start();
            t2.start();
            t3.start();
            t4.start();
            
            
            
        }
}




/**
 * 实现多线程的一种方式,继承Thread类,因为java类只能单继承,当不能使用继承时。就使用下面的另一个方式
 * @author Administrator
 *
 */
class MyThread extends Thread{
    //模拟一个多线程的Demo
    //定一个票数为100;
    private static int sum=100;
    @Override
    public void run() {
                //采用同步代码块实现线程安全
                while (true) {                
                    synchronized (MyThread02.class) {
                        if(sum<=0){
                            return;
                        }
                        sum--;
                        System.out.println(Thread.currentThread().getName()+"售出一张票;还剩余"+sum+"张");
                    }    
                    
                }
            }
        

    
}
/**
 * 实现多线程的第二种方式;实现Runnable接口
 * 
 * @author Administrator
 *
 */
class MyThread02 implements Runnable{
    //模拟一个多线程的Demo
    //定一个票数为100;
    private static int sum=100;
        @Override
        public void run() {
            //采用同步代码块实现线程安全
            while (true) {
                
                synchronized (MyThread02.class) {
                    if(sum<=0){
                        return;
                    }
                    sum--;
                    System.out.println(Thread.currentThread().getName()+"售出一张票;还剩余"+sum+"张");
                }    
                
            }
        }    
    
}

 全部都写在一个类里面了;直接新建一个类;复制,粘贴,导包就可以了

上一篇:原生jdbc操作mysql数据库详解


下一篇:数据库范式解析