/** * 解决多线程中线程安全的方式二:同步方法,操作共享数据的是一个方法 * 1.同步方法仍然涉及到同步监视器,只是不需要显示的声明 * 2.非静态的同步方法,同步监视器是this * 静态的同步方法,同步监视器是类本身(类.class) * * * */ public class ThreadMethodDemo { public static void main(String[] args) { RunnableImp1 runnableImp1 = new RunnableImp1(); Thread thread1 = new Thread(runnableImp1); Thread thread2 = new Thread(runnableImp1); Thread thread3 = new Thread(runnableImp1); thread1.setName("Runnable窗口1"); thread2.setName("Runnable窗口2"); thread3.setName("Runnable窗口3"); thread1.start(); thread2.start(); thread3.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } ThreadExtends threadExtends1 = new ThreadExtends(); ThreadExtends threadExtends2 = new ThreadExtends(); ThreadExtends threadExtends3 = new ThreadExtends(); threadExtends1.setName("Thread窗口1"); threadExtends2.setName("Thread窗口2"); threadExtends3.setName("Thread窗口3"); threadExtends1.start(); threadExtends2.start(); threadExtends3.start(); } } /*实现Runnable方式*/ class RunnableImp1 implements Runnable{ private int ticket = 100; @Override public void run() { while(true){ if(ticket > 0){ show(); }else{ break; } } } public synchronized void show(){//此处的synchronized相当于this if(ticket > 0){ System.out.println(Thread.currentThread().getName() + "卖票,票号为:" + ticket); ticket--; } } } class ThreadExtends1 extends Thread{ private static int ticket = 100; @Override public void run() { while(true){ if(ticket > 0){ show(); }else{ break; } } } public static synchronized void show(){//此处的synchronized相当于当前类对象(ThreadExtends1.class) if(ticket > 0){ System.out.println(Thread.currentThread().getName() + "卖票,票号为:" + ticket); ticket--; } } }
标签:Thread,start,安全,解决,new,ticket,多线程,public,ThreadExtends From: https://www.cnblogs.com/sjzchf/p/17076754.html