- ベストアンサー
Threadのターゲット切り替え方法とは?
ngsvxの回答
問題が2点あります。 1.ThreadSample#makingThreadParent()で、 threadp = new Thread(this); としていますが、このときのthisがインスタンス化されたクラスを指すこと。 つまり、makingThreadParent()はThreadSampleChildのインスタンスから呼んで いるので、thisはThreadSampleChildになります。 2.runメソッドがオーバーライドされている。 解決策としては、 ○ThreadSample#makingThreadParent()で、 threadp = new Thread( new ThreadSample() ); とする。 *この方法では、ThreadSampleはThreadSampleChildの変数を参照できません。 ○フラグを設定し、ThreadSampleChild#runメソッド内で分岐処理する。 つまり、 if(flag == PARENT){ super.run(); return; } をThreadSampleChild#runの最初に組み込んでおく。 *この方法では、親と子を同時には実行できません。 ○同時に実行する必要があり、しかも共通の変数を参照したいなら、 変数を保持するクラスを作り、making~のメソッドではthisを使わない。 (例) public void makingThreadParent(ThreadData data){ threadp = new Thread( new ThreadSample(data) ); } 何をしたいのかを明確にすれば、方法は決まってくると思います。
関連するQ&A
- java repaint()に関して
プログラムで以下のpaintComponents内のデバックができません。 理由は一体何なのでしょうか? お願いします。 import java.awt.Graphics; import javax.swing.JPanel; public class MainPanel extends JPanel implements Runnable { Thread th; public MainPanel() { super(); } public void movestart() { th = new Thread(this); th.start(); } public void paintComponent(Graphics g) { System.out.println("このデバックができない"); super.paintComponent(g); } public void run() { while (true) { System.out.println("ここのデバックはできている"); repaint(); try { th.sleep(100); } catch (Exception e) { } } } }
- ベストアンサー
- Java
- スレッド間の送受信のコードについて
下記のコードは、(以前お教え頂きました)『synchronized』を使用した、スレッド間の 送受信のコードですが、その代わりに、Interruptとか、Thread.sleep()を使用した、 コードに変更してみたいと思います。 Q1)そのコードをお教え頂けないでしょうか? class T_thread { public static void main(String args[]) { new rcvInterrupt().start(); } } class genInterrupt extends Thread { private rcvInterrupt target; genInterrupt(rcvInterrupt targetx) { this.target = targetx; } public void run() { System.out.println("genInterupt start"); for (int i = 0; i < 10; i++) { while (!target.isWaited) { // rcvInterruptがsynchronizedブロックに入るまで待ち合わせ // これがないと連続してsynchronizedしてしまう可能性がある } synchronized (target) { target.notifyAll(); target.isWaited = false; System.out.println("notify"); } } } } class rcvInterrupt extends Thread { volatile boolean isWaited; public synchronized void run() { new genInterrupt(this).start(); for (int i = 0; i < 10; i++) { try { isWaited = true; wait(); System.out.println("get interrupt cnt=" + i); } catch (InterruptedException e1) { } } } } 以上
- ベストアンサー
- Java
- 交互にスレッド実行 (どうしてちゃんと動いてる?)
http://oshiete1.goo.ne.jp/qa2968378.html で質問した者です。 2つのスレッドで1と2を交互に実行する以下のプログラム。 final Object obj1 = new Object(); //スレッド間通信用のobject final Object obj2 = new Object(); //スレッド間通信用のobject2 Thread t1 = new Thread() { public void run() { try { while(true) { System.out.print("1"); synchronized (obj1) { synchronized (obj2) { obj2.notify();//相手をnotifyして } obj1.wait();//自分はwait } } } catech (Exception e){} }; Thread t2 = new Thread() { public void run() { try { while(true) { System.out.print("2"); synchronized (obj2) { synchronized (obj1) { obj1.notify(); } obj2.wait(); } } } catch (Exception e){} } }; Thread t1 = new Test1(); Thread t2 = new Test2(); t1.start(); while(t1.getState() != Thread.State.WAITING); t2.start(); が思ったように動いてはいるものの、なぜ正常に動いているかがわかりません。 t1が wait() したときはobj1のロックをもっていて、t2の synchronized (obj1){obj1.notify()} ブロックに入れず待機するはずだと思うのですが。 なぜちゃんと動いているのでしょう?
- ベストアンサー
- Java
- wait中にinterruptを呼ばれたスレッドの振る舞いについて
はじめまして。javaの初心者です。 どうしてもわからないことがあります。 例えば、以下のコードで、 class Foo { public synchronized void foo() { while(条件) { try { this.wait(); } catch(InterruptedException ex) { 処理 } } } } wait中であったスレッドは、他のスレッドによって interrupt()メソッドを実行されたときは、Fooの ロックを取得してからcatch節を実行すると思うのですが、もし、以下のコードの場合は、 class Foo { public synchronized void foo() throws InterruptedException { while(条件) { this.wait(); } } } wait中であったスレッドは、他のスレッドによって interrupt()を実行されたときにすぐにInterrupted Exceptionをスローするのか、それとも Fooクラスのロックを取得してからInterruptedExceptionをスローするのかどちらなのか がわかりません。どうか教えてください。よろしく お願いします。
- ベストアンサー
- Java
- 別クラスのスレッドによるpaint()が上手くいきません!!
たびたびすみません、、、今度は別のクラスに記述したpaint()をメインでスレッド起動しても描写されません…オーバーライドか何かしなければいけないらしい情報を探し当てた気がするのですが、いまいちよくわかりません。。どうすればいいのでしょうか? 下に自分で作ってみたソースの抜粋を書きます。 import java.awt.*; import java.awt.event.*; class test extends Frame { subclass sc = new subclass(); Thread th=new Thread(sc); public static void main(String args[]) { test t=new test(); } public test() { setTitle("Test"); setSize(300,200); setVisible(true); th.start(); //閉じる addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } class subclass extends Frame implements Runnable { int i; public void run() { for(i=0;i<100;i++) { repaint(); } try { Thread.sleep(1000); } catch(InterruptedException e){} } public void paint(Graphics g) { g.drawOval(i,i,50,50); } } (EOS) どうか教えていただける方、お願いします!!
- 締切済み
- Java
- スレッドについて(長文です)
現在スレッドについて独学しています。array[0]に文字列を格納してそれを表示し、3秒間経った後に他のスレッドに通知し繰り返すというプログラムを作りたいのですが、以下のソースでコンパイルすると 5行目 型の開始が不正です try{ ^ 6行目 <identifier>がありません } ^ 18行目 シンボルを解釈処理できません シンボル:メソッドres(java.lang.String) 位置:Proのクラス pro.res(str2); ^ というコンパイルエラーがでます。模範解答と見比べてもかなりの部分が違います。このやり方では実現できないのでしょうか?なにぶん初心者なもので正しい答えとかけ離れた次元のプログラムを書いているかもしれませんがよろしくお願いします。 class Pro extends Thread{ String str; String array[] = new String[1]; try{ synchronized void res(String str){ this.str = str; array[0] = str; System.out.println(array[0]); Thread.sleep(((int)(Math.random() * 10) * 50) + 500); array[0] = "empty"; Thread.sleep(3000); notifyAll(); } } catch(Exception e1){ e1.printStackTrace(); } } class User extends Thread{ String str2; Pro pro; User(String str2,Pro pro){ this.str2 = str2; this.pro = pro; } public void run(){ while(true){ try{ if((pro.array[0]).equals("empty")){ pro.res(str2); } else{ wait(); } } catch(Exception e2){ e2.printStackTrace(); } } } } class NewRikai6{ public static void main(String args[]){ Pro pro = new Pro(); User user1 = new User("user1",pro); user1.start(); User user2 = new User("user2",pro); user2.start(); } }
- ベストアンサー
- Java
- スレッドについての質問です。
下記のロジックを見ていただきたいのです。 スレッドがnullの間はrunが動いています。 問題は一番下に記載した"stopplay()"というメソッドだと思われます、スレッドを停止して直ぐにまた動かしていますがどうもスレッドが二つ動いている様子です。なぜでしょうか? ************************************************** //最初にスレッドを開始します。 public init(){ play(); } ************************************************** //スレッドのON OFF public void threadOnOff(boolean sw) { if(sw == true){ thread =new Thread(this); thread.start(); } else { thread = null; } } ************************************************** //スレッド開始 public void play(){ threadOnOff(true); } ************************************************** //スレッド停止 public void stop(){ threadOnOff(false); } ************************************************** //runメソッド public void run(){ String mode = ""; while(thread != null){ try { thread.sleep(500); //0.5秒間隔で動きます。 mode = modeRequest(); if(mode.startsWith("STOP") == true) { //スレッド停止 threadOnOff(false); } } catch (InterruptedException ie) {} } } ************************************************** //問題のメソッドです。 public void stopplay(){ stop(); play(); }
- ベストアンサー
- Java
- TCP/IP通信について
現在、以下のようにTCP/IP通信のプログラミングを行っており、 サーバ/クライアント別々に4byteのデータ送信を10msec毎に10秒間行っております。 現在、WimdowsVista-Windows7間で各々をサーバ/クライアントとして順に起動し、 相互に4byte送信しているハズが、倍の8byteや12byteとデータが連なって送信されている 事象が発生してます。 OutputStreamではwrite後にflushを行っているので、flush契機でメモリ上に蓄えられた 送信用バッファが送信されるイメージでおりますが、4byteで送信できていないように見えます。 上記について、解決方法をご存じであればご教授お願い致します。 <Server.java> ===== public class Server { public static ServerSocket ss = null; public static Socket soc = null; private static InputStream is = null; private static OutputStream os = null; public static void main(String[] args) { try { // サーバソケット生成 ss = new ServerSocket(5000); soc = ss.accept(); is = soc.getInputStream(); os = soc.getOutputStream(); Thread rcvTh = new ServerRcvThread(is); rcvTh.start(); Thread sndTh = new ServerSndThread(os); sndTh.start(); // 10秒スリープ try{ Thread.sleep(10000); } catch ( Exception e){ e.printStackTrace(); } // スレッド停止 rcvTh.stop(); sndTh.stop(); } catch (IOException e) { e.printStackTrace(); } finally{ try { is.close(); os.close(); soc.close(); ss.close(); } catch (IOException e) { e.printStackTrace(); } } } } class ServerSndThread extends Thread{ private static OutputStream ous = null; ServerSndThread( OutputStream os ){ this.ous = os; } public void run(){ byte sndData[] = new byte[4]; sndData[0] = 0x01; sndData[1] = 0x02; sndData[2] = 0x03; sndData[3] = 0x04; try { while(true){ // データ書込み ous.write(sndData); ous.flush(); System.out.println("データ送信"); // 0.01秒スリープ try{ Thread.sleep(10); } catch ( Exception e){ e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } } class ServerRcvThread extends Thread{ private static InputStream ins = null; ServerRcvThread( InputStream os ){ this.ins = os; } public void run(){ byte rcvData[] = new byte[16]; int size = 0; try { while(true){ // データ読込み size = ins.read(rcvData); System.out.println("size:"+size+"byte"); } } catch (IOException e) { e.printStackTrace(); } } } ===== <Client.java> ===== public class Client { private static Socket soc = null; private static OutputStream os = null; private static InputStream is = null; public static void main(String[] args) { try { // ソケット生成 soc = new Socket("192.168.3.3", 5000); is = soc.getInputStream(); os = soc.getOutputStream(); Thread rcvTh = new ClientRcvThread(is); rcvTh.start(); Thread sndTh = new ClientSndThread(os); sndTh.start(); // 10秒スリープ try{ Thread.sleep(10000); } catch ( Exception e){ e.printStackTrace(); } // スレッド停止 rcvTh.stop(); sndTh.stop(); } catch (IOException e) { e.printStackTrace(); } finally{ try { is.close(); os.close(); soc.close(); } catch (IOException e) { e.printStackTrace(); } } } } class ClientSndThread extends Thread{ private static OutputStream ous = null; ClientSndThread( OutputStream os ){ this.ous = os; } public void run(){ byte sndData[] = new byte[4]; sndData[0] = 0x04; sndData[1] = 0x03; sndData[2] = 0x02; sndData[3] = 0x01; try { while(true){ // データ書込み ous.write(sndData); ous.flush(); System.out.println("データ送信"); // 0.01秒スリープ try{ Thread.sleep(10); } catch ( Exception e){ e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } } class ClientRcvThread extends Thread{ private static InputStream ins = null; ClientRcvThread( InputStream os ){ this.ins = os; } public void run(){ byte rcvData[] = new byte[16]; int size = 0; try { while(true){ // データ読込み size = ins.read(rcvData); System.out.println("size:"+size+"byte"); } } catch (IOException e) { e.printStackTrace(); } } } =====
- ベストアンサー
- Java
- 初心者です。
javaのソースについて質問です。 次のソースに関していくつか質問させて下さい。 public class HelloThread implements Runnable { //処理1 Thread th; int pause; public static void main(String args[]) { HelloThread hello; //処理2 hello = new HelloThread(); hello.start(); //処理3 try{ Thread.sleep(1000); } catch (Exception ex) { } //処理4 hello.stop(); } public HelloThread() { } public void start() { //処理5 th = new Thread(this); th.start(); } public void run() { //処理6 while(th != null) { System.out.println("Hello World!"); try { Thread.sleep(200); } catch (Exception ex) { } } } public void stop() { //処理7 th = null; } } 質問 (1)mainメソッドのhello = new HelloThread();で HelloThreadクラスの処理1の2行が実行されると 思いますが、その後にhello.start();が実行される のでしょうか? (2)hello.start();で処理5が実行されるのでしょうか? (3)th.start();でrun()が呼び出されるのでしょうか? (4)処理6を実行している間、処理3、4が実行される のでしょうか? 出来ればその理由も教えて下さい。 (5)このソースの処理4の後のpublic HelloThread()は 何か意味があるのでしょうか? 以上、初心的な質問だと思いますが、よろしくお願いします。
- ベストアンサー
- Java
- repaint処理が実行されなくなる時があります
下記のように1秒周期で描画更新するように していますが、repaint処理が実行されなくなる ことがあります。repaintからupdateが呼び出されて いないことまでは判ったのですが、このような ことがあるのでしょうか?また、回避策があれば 教えて下さい。 ------------------------------------------------ public void run() { try { while ( m_bLoopFlag ) { repaint(); Thread.sleep( 1000 ); } } catch( Exception e ) { } finally { m_bEndFlag = true; } } public void update( Graphics g ) { paint( g ); }
- ベストアンサー
- Java
お礼
どうもありがとうございました。 すごく参考になりました。