public static void main(String[] args) {
SellThread st = new SellThread()
Thread th1 = new Thread(st)
th1.start()
Thread th2 = new Thread(st)
th2.start()
Thread th3 = new Thread(st)
th3.start()
}
}
class SellThread implements Runnable {
private int number=10
String s = new String()
public void run() {
while (number >0) {
synchronized (s) {
System.out.println("第" + number + "个人在"
+ Thread.currentThread().getName() + "买票")
}
number--
try {
Thread.sleep(10)
} catch (InterruptedException e) {
e.printStackTrace()
}
}
}
}
synchronized (s)的s是synchronized 的参数,synchronized 的参数可以是任意对象,我定义了一个String类型的首悔对象s,方便看信者程序而已。
但是要注意者坦正,s的定义一定要在run方法之外,不然还会出现负数。因为你启动了3个线程,每个线程都调用了run方法,在每个线程就会在run方法里边产生自己的s对象,一共会产生3个,达不到同步的目的。
如果还有不明白的,可以继续问。
楼上答案是正解,你一直用一个对象的在set,共享了同一个对象.其实也没用新建5个对象.可以谨源set之后就开始执行.但是多线程的唯核意义可能不大了.
package com.experiment9
public class Ticket extends Thread {
public Ticket(String s){
super(s)
}
int num=100 //静态变量
public void run(){
while(true){
synchronized (" "){ //同步块实现多线程
if(num>0){
try {
Thread.sleep(500) //线程休眠10毫秒
}catch (Exception e){
e.printStackTrace()
}
System.out.println(this.getName()+"------------------------"+(num--))
}
}
}
}
public static void main(String[] args) {//main 函数
Ticket ticket =new Ticket("5号窗口")
Thread thread_5=new Thread(ticket)
ticket.setName("一号窗口")
thread_5.start()
Thread thread_1=new Thread(ticket)
ticket.setName("二号窗口")
thread_1.start()
Thread thread_2=new Thread(ticket)
ticket.setName("三号窗口")
thread_2.start()
Thread thread_3=new Thread(ticket)
ticket.setName("四号窗口") //为什么前面祥山态的set那么没用呢?
thread_3.start()
Thread thread_4=new Thread(ticket)
thread_4.start()
}
}
这是线程同步问题
修改如下
using Systemusing System.Collections.Generic
using System.IO
using System.Linq
using System.Threading
namespace ConsoleApplication1
{
class TestThread
{
//volatile将禁止将num优化到各个线程的存储区中
volatile int num = 50
//用于lock
object sync = new object()
public void SellTicket()
{
for (int i = 50 i > 0 i--)
{
敬袭 lock (sync)
{
if (num > 0)
{
Console.WriteLine(Thread.CurrentThread.Name +
"卖出了第" + num + "张")
num--
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
TestThread a = new TestThread()//多线程模式。5
Thread mythr1 = new Thread(a.SellTicket)
mythr1.Name = "窗口一"
Thread mythr2 = new Thread(a.SellTicket)
如笑 mythr2.Name = "窗口二"
Thread mythr3 = new Thread(a.SellTicket)
mythr3.Name = "窗口三渣稿含"
mythr1.Start()
mythr2.Start()
mythr3.Start()
Console.ReadKey()
}
}
}
这样就正常了
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)