标签:
package com.ilaoda.day0912; public class MyThreadDemo { public static void main(String[] args) { MyThread my1 = new MyThread(); MyThread my2 = new MyThread(); my1.start(); //开启线程 my2.start(); } } // 继承Thread类 class MyThread extends Thread { @Override public void run() { //运行线程 for (int x = 0; x < 200; x++) { System.out.println(x); } } }
package cn.itcast_05; /* * 方式2:实现Runnable接口 * 步骤: * A:自定义类MyRunnable实现Runnable接口 * B:重写run()方法 * C:创建MyRunnable类的对象 * D:创建Thread类的对象,并把C步骤的对象作为构造参数传递 */ public class MyRunnableDemo { public static void main(String[] args) { // 创建MyRunnable类的对象 MyRunnable my = new MyRunnable(); Thread t1 = new Thread(my, "林青霞"); Thread t2 = new Thread(my, "刘意"); t1.start(); t2.start(); } } class MyRunnable implements Runnable { @Override public void run() { for (int x = 0; x < 100; x++) { // 由于实现接口的方式就不能直接使用Thread类的方法了,但是可以间接的使用 System.out.println(Thread.currentThread().getName() + ":" + x); } } }
synchronized(锁对象) { 需要被同步的代码; }
public void run() { while (true) { synchronized (obj) { if (tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在出售第" + (tickets--) + "张票"); } } } }
public void run() { while (true) { if(x%2==0){ synchronized (this) { //锁对象 if (tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在出售第" + (tickets--) + "张票 "); } } }else { sellTicket(); } x++; } } private synchronized void sellTicket() { if (tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在出售第" + (tickets--) + "张票 "); } }
public void run() { while (true) { if(x%2==0){ synchronized (SellTicket.class) { //锁对象 if (tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在出售第" + (tickets--) + "张票 "); } } }else { sellTicket(); } x++; } } private static synchronized void sellTicket() { if (tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "正在出售第" + (tickets--) + "张票 "); } }
线程安全的类:
标签:
原文地址:http://my.oschina.net/ilaoda/blog/505621