面试题--多线程互斥(线程安全)

来源:互联网 发布:网络广播电台小川 编辑:程序博客网 时间:2024/04/23 19:32

问题描述:两个线程交替的输出字符串


输出描述:

hhhhhhh
eeeeeee
hhhhhhh
eeeeeee
hhhhhhh
eeeeeee


代码显示:

package ThreadTest;/*********************************** * ************ 线程的互斥 ************** * 线程安全性问题可以用银行家转账来解释。 * 使用 synchronized 代码块或者 synchronized方法来解决问题 * 但是synchronized必须持有 同一把锁 才可以实现互斥 * 1、synchronized (this) 和  synchronized方法 * 2、synchronized (this) 和  static 方法下使用   synchronized (Outputer.class)  * *********** 2016.04.25 *********** * ********************************/public class TraditionalThreadSynchronized {public static void main(String[] args) {// TODO Auto-generated method stubnew TraditionalThreadSynchronized().init();}//Outputer outputer = new Outputer();/************************************************** * 在main方法中直接Outputer outputer = new Outputer();时出现问题?   *·原因·*: 因为在静态方法内不能new内部类的实例对象,为什么?*因为内部类可以访问外部类的成员变量,但是在main方法中,并未new TraditionalThreadSynchronized(),*所以,根本没有外部类的成员变量。要想创建内部类的实例对象,必须要有外部类的实例对象。*解决办法:*     利用init()方法创建外部类对象,并把main中的方法实体放在init()中。 **************************************************************/private void init(){Outputer outputer = new Outputer();new Thread(new Runnable(){public void run(){while(true){try {Thread.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}outputer.output("hhhhhhh");}}}).start();new Thread(new Runnable(){public void run(){while(true){try {Thread.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}outputer.output1("eeeeeee");//如果变成new Outputer().output("某某某")//就没有办法实现synchronized 同步了,因为这个时候是a线程有自己的,//b线程有自己的输出,各玩各的,不是同一个输出实例}}}).start();}static class Outputer{void output(String name){/*该段代码要保持原子性,排他性 *但是该处用  name 达不到互斥的作用 * synchronized (name)  * 因为达到互斥必须是:同一个对象!!! * 解决:1、创建同一个对象: *    String xxx = ""; *    synchronized(xxx); *    因为xxx是同一个对象。 *    2、将互斥量指向  共同调用的对象:this *    synchronized (this) * */synchronized (this) {for(int i=0; i<name.length(); i++ ){System.out.print(name.charAt(i));}System.out.println();}}/*对整个方法添加互斥条件: *  * */synchronized void output1(String name){for(int i=0; i<name.length(); i++ ){System.out.print(name.charAt(i));}System.out.println();}           static void output2(String name){           synchronized (Outputer.class) {for(int i=0; i<name.length(); i++ ){System.out.print(name.charAt(i));}System.out.println();}/* * output 和 output2不可以实现同步, * 要实现同步,需要把output修改为: **************************************** * synchronized (Outputer.class) {for(int i=0; i<name.length(); i++ ){System.out.print(name.charAt(i));}System.out.println();}保持锁对象的一致!!!!必须是同一把锁才能保证 互斥的一致性 ****************************************/}}}


1 0
原创粉丝点击